3
3
//same buffer to avoid memcpy and limit memory allocations
4
4
var Writer = function ( size ) {
5
5
this . size = size || 1024 ;
6
- this . buffer = new Buffer ( this . size + 5 ) ;
6
+ this . buffer = Buffer ( this . size + 5 ) ;
7
7
this . offset = 5 ;
8
8
this . headerPosition = 0 ;
9
9
} ;
@@ -15,7 +15,7 @@ p._ensure = function(size) {
15
15
var remaining = this . buffer . length - this . offset ;
16
16
if ( remaining < size ) {
17
17
var oldBuffer = this . buffer ;
18
- this . buffer = Buffer ( oldBuffer . length + size ) ;
18
+ this . buffer = new Buffer ( oldBuffer . length + size ) ;
19
19
oldBuffer . copy ( this . buffer ) ;
20
20
}
21
21
}
@@ -36,24 +36,36 @@ p.addInt16 = function(num) {
36
36
return this ;
37
37
}
38
38
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
+
39
51
p . addCString = function ( string ) {
40
52
//just write a 0 for empty or null strings
41
53
if ( ! string ) {
42
54
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 ;
45
60
}
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
51
63
return this ;
52
64
}
53
65
54
66
p . addChar = function ( char ) {
55
67
this . _ensure ( 1 ) ;
56
- this . buffer . write ( char , this . offset ) ;
68
+ writeString ( this . buffer , char , this . offset , 1 ) ;
57
69
this . offset ++ ;
58
70
return this ;
59
71
}
0 commit comments