File tree Expand file tree Collapse file tree 2 files changed +47
-0
lines changed Expand file tree Collapse file tree 2 files changed +47
-0
lines changed Original file line number Diff line number Diff line change @@ -837,6 +837,33 @@ export class DynamicBuffer {
837837 return this ;
838838 }
839839
840+ /**
841+ * Returns a new Buffer that references the same memory as the original, but offset and cropped
842+ * by the start and end indices.
843+ *
844+ * ```ts
845+ * const buf = new DynamicBuffer('ABCD');
846+ * const sub = buf.subarray(1, 3);
847+ * sub[0] = 67;
848+ * sub[1] = 66;
849+ * console.log(buf.toString());
850+ * // ACBD
851+ * ```
852+ *
853+ * @param start Where the new `Buffer` will start, default 0.
854+ * @param end Where the new `Buffer` will end (not inclusive), default the length of this buffer.
855+ * @returns The new buffer.
856+ */
857+ subarray ( start : number = 0 , end : number = this . length ) : Buffer {
858+ const { startOffset, endOffset } = this . calculateOffsets ( start , end ) ;
859+
860+ if ( ! this . buffer || this . length === 0 ) {
861+ return Buffer . alloc ( 0 ) ;
862+ }
863+
864+ return this . buffer ?. subarray ( startOffset , endOffset ) ;
865+ }
866+
840867 /**
841868 * Write data into internal buffer with the specified offset.
842869 *
Original file line number Diff line number Diff line change @@ -111,6 +111,26 @@ describe('Resize tests', () => {
111111 } ) ;
112112} ) ;
113113
114+ describe ( 'Subarray test' , ( ) => {
115+ it ( 'Test subarray' , ( ) => {
116+ const buf = new DynamicBuffer ( 'ABCDEF' ) ;
117+ const sub = buf . subarray ( 1 , 3 ) ;
118+ sub [ 0 ] = 67 ;
119+ sub [ 1 ] = 66 ;
120+
121+ assert . equal ( buf . toString ( ) , 'ACBDEF' ) ;
122+ } ) ;
123+
124+ it ( 'Test subarray with empty buffer' , ( ) => {
125+ const buf = new DynamicBuffer ( ) ;
126+ const sub = buf . subarray ( 1 , 3 ) ;
127+ sub [ 0 ] = 67 ;
128+ sub [ 1 ] = 66 ;
129+
130+ assert . equal ( buf . toString ( ) , '' ) ;
131+ } ) ;
132+ } ) ;
133+
114134describe ( 'Tools methods test' , ( ) => {
115135 it ( 'Test isDynamicBuffer util method' , ( ) => {
116136 assert . equal ( isDynamicBuffer ( Buffer . from ( '' ) ) , false ) ;
You can’t perform that action at this time.
0 commit comments