@@ -393,3 +393,69 @@ test("should return error on more than 8 packed bools", () => {
393393 Error ( "cannot pack more than 8 bools into a single byte" ) ,
394394 )
395395} )
396+
397+ test ( "should write and read arrays of u8" , ( ) => {
398+ const bf = new Bufferfish ( )
399+
400+ const numbers = [ 1 , 2 , 3 , 4 , 5 ]
401+ bf . writeArray ( numbers , ( n ) => bf . writeUint8 ( n ) )
402+
403+ expect ( bf . view ( ) ) . toEqual ( new Uint8Array ( [ 0 , 5 , 1 , 2 , 3 , 4 , 5 ] ) )
404+
405+ const readArray = bf . readArray ( ( ) => {
406+ const val = bf . readUint8 ( )
407+ if ( val instanceof Error ) {
408+ throw val
409+ }
410+ return val
411+ } )
412+
413+ expect ( readArray ) . toEqual ( numbers )
414+ } )
415+
416+ test ( "should write and read arrays of strings" , ( ) => {
417+ const bf = new Bufferfish ( )
418+
419+ const strings = [ "hello" , "world" , "bufferfish" ]
420+ bf . writeArray ( strings , ( s ) => bf . writeString ( s ) )
421+
422+ const readArray = bf . readArray ( ( ) => {
423+ const val = bf . readString ( )
424+ if ( val instanceof Error ) {
425+ throw val
426+ }
427+ return val
428+ } )
429+
430+ expect ( readArray ) . toEqual ( strings )
431+ } )
432+
433+ test ( "should handle empty arrays" , ( ) => {
434+ const bf = new Bufferfish ( )
435+
436+ const emptyArray : number [ ] = [ ]
437+ bf . writeArray ( emptyArray , ( n ) => bf . writeUint8 ( n ) )
438+
439+ expect ( bf . view ( ) ) . toEqual ( new Uint8Array ( [ 0 , 0 ] ) )
440+
441+ const readArray = bf . readArray ( ( ) => {
442+ const val = bf . readUint8 ( )
443+ if ( val instanceof Error ) {
444+ throw val
445+ }
446+ return val
447+ } )
448+
449+ expect ( readArray ) . toEqual ( emptyArray )
450+ } )
451+
452+ test ( "should return error for arrays exceeding maximum length" , ( ) => {
453+ const bf = new Bufferfish ( )
454+
455+ const hugeArray = new Array ( 65536 ) . fill ( 1 )
456+
457+ const err = bf . writeArray ( hugeArray , ( n ) => bf . writeUint8 ( n ) )
458+ expect ( err ) . toEqual (
459+ Error ( "array length 65536 exceeds maximum size of 65535" ) ,
460+ )
461+ } )
0 commit comments