Skip to content

Commit 6e99863

Browse files
committed
feat: add set method.
1 parent 7bd3360 commit 6e99863

File tree

2 files changed

+54
-1
lines changed

2 files changed

+54
-1
lines changed

src/dynamicBuffer.ts

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { constants } from 'buffer';
22

33
import { DynamicBufferIterator } from './iterator';
4-
import { checkRange, swap } from './utils';
4+
import { checkBounds, checkRange, swap } from './utils';
55

66
/**
77
* The character encoding that is supported by Node.js, copy from Node.js Buffer module.
@@ -625,6 +625,24 @@ export class DynamicBuffer {
625625
return this;
626626
}
627627

628+
/**
629+
* Sets a value or an array of values.
630+
*
631+
* @param array A typed or untyped array of values to set.
632+
* @param offset The index in the current array at which the values are to be written.
633+
*/
634+
set(array: ArrayLike<number>, offset: number = 0): void {
635+
if (array.length > 0) {
636+
checkBounds('offset', offset, 0, this.length - array.length);
637+
}
638+
639+
if (!this.buffer || this.length <= 0) {
640+
return;
641+
}
642+
643+
this.subarray(0, this.length).set(array, offset);
644+
}
645+
628646
/**
629647
* Returns a new Buffer that references the same memory as the original, but offset and cropped
630648
* by the start and end indices.

test/write.spec.ts

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,3 +209,38 @@ describe('Write tests', () => {
209209
});
210210
});
211211
});
212+
213+
describe('Set tests', () => {
214+
it('Test set', () => {
215+
const buf = new DynamicBuffer('hello');
216+
217+
buf.set([97], 1);
218+
219+
assert.equal(buf.toString(), 'hallo');
220+
});
221+
222+
it('Test set of empty buffer', () => {
223+
const buf = new DynamicBuffer();
224+
225+
assert.doesNotThrow(() => {
226+
buf.set([]);
227+
});
228+
229+
assert.throws(() => {
230+
buf.set([97]);
231+
});
232+
});
233+
234+
it('Test set offset parameter', () => {
235+
const buf = new DynamicBuffer('xxxxx');
236+
237+
assert.doesNotThrow(() => {
238+
buf.set([97, 98], 3);
239+
});
240+
assert.equal(buf.toString(), 'xxxab');
241+
242+
assert.throws(() => {
243+
buf.set([97, 98], 4);
244+
});
245+
});
246+
});

0 commit comments

Comments
 (0)