File tree Expand file tree Collapse file tree 2 files changed +54
-1
lines changed Expand file tree Collapse file tree 2 files changed +54
-1
lines changed Original file line number Diff line number Diff line change 11import { constants } from 'buffer' ;
22
33import { 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.
Original file line number Diff line number Diff 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+ } ) ;
You can’t perform that action at this time.
0 commit comments