Skip to content

Commit 86c8322

Browse files
committed
feat: add length getter.
- Add length getter to getting the number of in-use bytes. - Update test cases to testing length getter. - Update readme.
1 parent d05d9b5 commit 86c8322

File tree

3 files changed

+13
-2
lines changed

3 files changed

+13
-2
lines changed

README.md

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ yarn add dynamic-buffer
3232
2. Creates `DynamicBuffer` instance with default initial size or the specific size:
3333

3434
```ts
35-
const buffer = new DynamicBuffer({ size: 12 });
35+
const buffer = new DynamicBuffer();
3636
```
3737

3838
3. Appends data into buffer:
@@ -42,9 +42,11 @@ yarn add dynamic-buffer
4242
buffer.append('world!');
4343
```
4444

45-
4. Exports data to string or builtin buffer object:
45+
4. Exports data to string or builtin buffer object without unused bytes:
4646

4747
```ts
48+
console.log(buffer.length);
49+
// 12
4850
const buf = buffer.toBuffer();
4951
console.log(buf.toString());
5052
// Hello world!

src/dynamicBuffer.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,13 @@ export class DynamicBuffer {
8585
}
8686
}
8787

88+
/**
89+
* Returns the number of the used bytes in this buffer.
90+
*/
91+
get length() {
92+
return this.used;
93+
}
94+
8895
/**
8996
* Appends string to this buffer according to the character encoding.
9097
*

test/dynamicBuffer.spec.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ describe('Initialization tests', () => {
1010

1111
assert.equal(Reflect.get(buffer, 'size'), Reflect.get(buffer, 'DefaultInitialSize'));
1212
assert.notEqual(Reflect.get(buffer, 'buffer'), undefined);
13+
assert.equal(buffer.length, 0);
1314
});
1415

1516
it('Test initializing with zero size', () => {
@@ -53,6 +54,7 @@ describe('Append tests', () => {
5354
count = buffer.append(str);
5455
assert.equal(count, str.length);
5556
assert.equal(buffer.toString(), 'Hello world');
57+
assert.equal(buffer.length, 'Hello world'.length);
5658
});
5759

5860
it('Test appending empty string', () => {

0 commit comments

Comments
 (0)