@@ -17,6 +17,21 @@ SlowBuffer.prototype.inspect = function() {
1717} ;
1818
1919
20+ SlowBuffer . prototype . hexSlice = function ( start , end ) {
21+ var len = this . length ;
22+
23+ if ( ! start || start < 0 ) start = 0 ;
24+ if ( end < 0 || start + end > len ) end = len - start ;
25+
26+ var out = '' ;
27+ for ( var i = start ; i < end ; i ++ ) {
28+ out += toHex ( this [ i ] ) ;
29+ }
30+ return out ;
31+ } ;
32+
33+
34+
2035SlowBuffer . prototype . toString = function ( encoding , start , end ) {
2136 encoding = String ( encoding || 'utf8' ) . toLowerCase ( ) ;
2237 start = + start || 0 ;
@@ -28,6 +43,9 @@ SlowBuffer.prototype.toString = function(encoding, start, end) {
2843 }
2944
3045 switch ( encoding ) {
46+ case 'hex' :
47+ return this . hexSlice ( start , end ) ;
48+
3149 case 'utf8' :
3250 case 'utf-8' :
3351 return this . utf8Slice ( start , end ) ;
@@ -51,6 +69,23 @@ SlowBuffer.prototype.toString = function(encoding, start, end) {
5169} ;
5270
5371
72+ SlowBuffer . prototype . hexWrite = function ( string , offset ) {
73+ var len = string . length ;
74+ offset = + offset || 0 ;
75+
76+ // must be an even number of digits
77+ if ( len % 2 ) {
78+ throw new Error ( 'Invalid hex string' ) ;
79+ }
80+ for ( var i = 0 ; i < len / 2 ; i ++ ) {
81+ var byte = parseInt ( string . substr ( i * 2 , 2 ) , 16 ) ;
82+ if ( isNaN ( byte ) ) throw new Error ( 'Invalid hex string' ) ;
83+ this [ offset + i ] = byte ;
84+ }
85+ return i ;
86+ }
87+
88+
5489SlowBuffer . prototype . write = function ( string , offset , encoding ) {
5590 // Support both (string, offset, encoding)
5691 // and the legacy (string, encoding, offset)
@@ -64,6 +99,9 @@ SlowBuffer.prototype.write = function(string, offset, encoding) {
6499 encoding = String ( encoding || 'utf8' ) . toLowerCase ( ) ;
65100
66101 switch ( encoding ) {
102+ case 'hex' :
103+ return this . hexWrite ( string , offset ) ;
104+
67105 case 'utf8' :
68106 case 'utf-8' :
69107 return this . utf8Write ( string , offset ) ;
@@ -224,6 +262,10 @@ Buffer.prototype.write = function(string, offset, encoding) {
224262
225263 var ret ;
226264 switch ( encoding ) {
265+ case 'hex' :
266+ ret = this . parent . hexWrite ( string , this . offset + offset , maxLength ) ;
267+ break ;
268+
227269 case 'utf8' :
228270 case 'utf-8' :
229271 ret = this . parent . utf8Write ( string , this . offset + offset , maxLength ) ;
@@ -277,6 +319,9 @@ Buffer.prototype.toString = function(encoding, start, end) {
277319 end = end + this . offset ;
278320
279321 switch ( encoding ) {
322+ case 'hex' :
323+ return this . parent . hexSlice ( start , end ) ;
324+
280325 case 'utf8' :
281326 case 'utf-8' :
282327 return this . parent . utf8Slice ( start , end ) ;
0 commit comments