Skip to content

Commit c0a59bc

Browse files
committed
feat: add toJSON method.
1 parent 86c8322 commit c0a59bc

File tree

3 files changed

+55
-0
lines changed

3 files changed

+55
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,3 +79,5 @@ yarn add dynamic-buffer
7979
- `encoding`: The character encoding for output string.
8080
- `start`: The start byte offset.
8181
- `end`: The end byte offset.
82+
83+
- `toJSON()`: Exports data to a JSON representation.

src/dynamicBuffer.ts

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,36 @@ export class DynamicBuffer {
196196
return this.buffer.toString(encoding || this.encoding, startOffset, endOffset);
197197
}
198198

199+
/**
200+
* Returns a JSON representation of this buffer.
201+
*
202+
* ```js
203+
* const buf = new DynamicBuffer();
204+
* buf.append("Hello");
205+
* console.log(JSON.stringify(buf));
206+
* // {"type":"Buffer","data":[72,101,108,108,111]}
207+
* ```
208+
*/
209+
toJSON() {
210+
const data: number[] = [];
211+
212+
if (this.buffer && this.used > 0) {
213+
// eslint-disable-next-line no-restricted-syntax
214+
for (const pair of this.buffer.entries()) {
215+
if (pair[0] >= this.used) {
216+
break;
217+
}
218+
219+
data.push(pair[1]);
220+
}
221+
}
222+
223+
return {
224+
type: 'Buffer',
225+
data,
226+
};
227+
}
228+
199229
/**
200230
* Ensures the buffer size is at least equal to the expect size.
201231
*

test/dynamicBuffer.spec.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,29 @@ describe('Export string tests', () => {
213213
});
214214
});
215215

216+
describe('Exports to JSON object', () => {
217+
it('Test toJSON() without writes data', () => {
218+
const buffer = new DynamicBuffer();
219+
220+
const buf = buffer.toJSON();
221+
222+
assert.equal(buf.type, 'Buffer');
223+
assert.deepEqual(buf.data, []);
224+
assert.equal(JSON.stringify(buf), '{"type":"Buffer","data":[]}');
225+
});
226+
227+
it('Test toJSON() with data', () => {
228+
const buffer = new DynamicBuffer();
229+
230+
buffer.append('Hello');
231+
const buf = buffer.toJSON();
232+
233+
assert.equal(buf.type, 'Buffer');
234+
assert.deepEqual(buf.data, [72, 101, 108, 108, 111]);
235+
assert.equal(JSON.stringify(buf), '{"type":"Buffer","data":[72,101,108,108,111]}');
236+
});
237+
});
238+
216239
describe('Resize tests', () => {
217240
it('Test resize()', () => {
218241
const buffer = new DynamicBuffer();

0 commit comments

Comments
 (0)