File tree Expand file tree Collapse file tree 2 files changed +29
-10
lines changed
Expand file tree Collapse file tree 2 files changed +29
-10
lines changed Original file line number Diff line number Diff line change @@ -3,19 +3,28 @@ import { StringEncoding } from "./StringEncoding"
33
44export class StringWriter extends Writable {
55
6- protected buf = Buffer . alloc ( 0 )
6+ protected byteLength = 0
7+ protected bufs : Buffer < ArrayBuffer > [ ] = [ ]
8+
9+ constructor ( protected maxByteLength : number = 1 * 1024 * 1024 ) {
10+ super ( )
11+ }
712
813 _write ( chunk : Buffer | string | any , _ : string , callback : ( error : Error | null ) => void ) {
9- if ( chunk instanceof Buffer ) {
10- this . buf = Buffer . concat ( [ this . buf , chunk ] )
11- callback ( null )
12- }
13- else {
14- callback ( new Error ( "StringWriter expects chunks of type 'Buffer'." ) )
14+ if ( ! ( chunk instanceof Buffer ) ) {
15+ callback ( new Error ( "StringWriter: expects chunks of type 'Buffer'." ) )
16+ return
17+ }
18+ if ( this . byteLength + chunk . byteLength > this . maxByteLength ) {
19+ callback ( new Error ( `StringWriter: Out of bounds. (maxByteLength=${ this . maxByteLength } )` ) )
20+ return
1521 }
22+ this . byteLength += chunk . byteLength
23+ this . bufs . push ( chunk )
24+ callback ( null )
1625 }
1726
1827 getText ( encoding : StringEncoding ) {
19- return this . buf . toString ( encoding )
28+ return Buffer . concat ( this . bufs ) . toString ( encoding ) ;
2029 }
2130}
Original file line number Diff line number Diff line change @@ -3,17 +3,27 @@ const { StringWriter } = require("../dist/StringWriter")
33
44describe ( "StringWriter" , function ( ) {
55 it ( "can run write string result" , function ( ) {
6- const w = new StringWriter ( )
6+ const w = new StringWriter ( 10000 )
77 w . write ( Buffer . from ( "hello" ) )
88 w . write ( Buffer . from ( "world" ) )
99 w . end ( )
1010 assert . equal ( w . getText ( "utf-8" ) , "helloworld" )
1111 } )
1212
1313 it ( "can handle chunked multi-byte unicode codepoints" , function ( ) {
14- const w = new StringWriter ( )
14+ const w = new StringWriter ( 10000 )
1515 w . write ( Buffer . from ( [ 0xE2 , 0x82 ] ) )
1616 w . end ( Buffer . from ( [ 0xAC ] ) )
1717 assert . equal ( w . getText ( "utf-8" ) , "€" )
1818 } )
19+
20+ it ( "fails if out of bounds" , function ( done ) {
21+ const w = new StringWriter ( 10 )
22+ w . once ( "error" , ( err ) => {
23+ assert . match ( err . message , / o u t o f b o u n d s / i)
24+ done ( )
25+ } )
26+ w . write ( Buffer . from ( "hello" ) )
27+ w . write ( Buffer . from ( "worldworldworld" ) )
28+ } )
1929} ) ;
You can’t perform that action at this time.
0 commit comments