33//same buffer to avoid memcpy and limit memory allocations
44var Writer = function ( size ) {
55 this . size = size || 1024 ;
6- this . buffer = new Buffer ( this . size + 5 ) ;
6+ this . buffer = Buffer ( this . size + 5 ) ;
77 this . offset = 5 ;
88 this . headerPosition = 0 ;
99} ;
@@ -15,7 +15,7 @@ p._ensure = function(size) {
1515 var remaining = this . buffer . length - this . offset ;
1616 if ( remaining < size ) {
1717 var oldBuffer = this . buffer ;
18- this . buffer = Buffer ( oldBuffer . length + size ) ;
18+ this . buffer = new Buffer ( oldBuffer . length + size ) ;
1919 oldBuffer . copy ( this . buffer ) ;
2020 }
2121}
@@ -36,24 +36,36 @@ p.addInt16 = function(num) {
3636 return this ;
3737}
3838
39+ //for versions of node requiring 'length' as 3rd argument to buffer.write
40+ var writeString = function ( buffer , string , offset , len ) {
41+ buffer . write ( string , offset , len ) ;
42+ }
43+
44+ //overwrite function for older versions of node
45+ if ( Buffer . prototype . write . length === 3 ) {
46+ writeString = function ( buffer , string , offset , len ) {
47+ buffer . write ( string , offset ) ;
48+ }
49+ }
50+
3951p . addCString = function ( string ) {
4052 //just write a 0 for empty or null strings
4153 if ( ! string ) {
4254 this . _ensure ( 1 ) ;
43- this . buffer [ this . offset ++ ] = 0 ;
44- return this ;
55+ } else {
56+ var len = Buffer . byteLength ( string ) ;
57+ this . _ensure ( len + 1 ) ; //+1 for null terminator
58+ writeString ( this . buffer , string , this . offset , len ) ;
59+ this . offset += len ;
4560 }
46- var len = Buffer . byteLength ( string ) + 1 ;
47- this . _ensure ( len ) ;
48- this . buffer . write ( string , this . offset ) ;
49- this . offset += len ;
50- this . buffer [ this . offset ] = 0 ; //add null terminator
61+
62+ this . buffer [ this . offset ++ ] = 0 ; // null terminator
5163 return this ;
5264}
5365
5466p . addChar = function ( char ) {
5567 this . _ensure ( 1 ) ;
56- this . buffer . write ( char , this . offset ) ;
68+ writeString ( this . buffer , char , this . offset , 1 ) ;
5769 this . offset ++ ;
5870 return this ;
5971}
0 commit comments