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
} ;
@@ -36,14 +36,26 @@ 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
55
} else {
44
56
var len = Buffer . byteLength ( string ) ;
45
57
this . _ensure ( len + 1 ) ; //+1 for null terminator
46
- this . buffer . write ( string , this . offset , len ) ;
58
+ writeString ( this . buffer , string , this . offset , len ) ;
47
59
this . offset += len ;
48
60
}
49
61
@@ -53,7 +65,7 @@ p.addCString = function(string) {
53
65
54
66
p . addChar = function ( char ) {
55
67
this . _ensure ( 1 ) ;
56
- this . buffer . write ( char , this . offset , 1 ) ;
68
+ writeString ( this . buffer , char , this . offset , 1 ) ;
57
69
this . offset ++ ;
58
70
return this ;
59
71
}
0 commit comments