@@ -270,6 +270,12 @@ function is_one_of(o, typelist) {
270270 }
271271 return false ;
272272}
273+ function buffer_zero ( b , len , neg ) {
274+ for ( var i = 0 ; i < len && i < b . length ; i ++ ) {
275+ if ( b [ i ] !== ( neg ? 0xff : 0 ) ) return false ;
276+ }
277+ return true ;
278+ }
273279types . is_ulong = function ( o ) {
274280 return is_one_of ( o , [ types . Ulong , types . Ulong0 , types . SmallUlong ] ) ;
275281} ;
@@ -290,8 +296,13 @@ types.wrap_boolean = function(v) {
290296 return v ? new types . True ( ) : new types . False ( ) ;
291297} ;
292298types . wrap_ulong = function ( l ) {
293- if ( l === 0 ) return new types . Ulong0 ( ) ;
294- else return l > 255 ? new types . Ulong ( l ) : new types . SmallUlong ( l ) ;
299+ if ( Buffer . isBuffer ( l ) ) {
300+ if ( buffer_zero ( l , 8 , false ) ) return new types . Ulong0 ( ) ;
301+ return buffer_zero ( l , 7 , false ) ? new types . SmallUlong ( l [ 7 ] ) : new types . Ulong ( l ) ;
302+ } else {
303+ if ( l === 0 ) return new types . Ulong0 ( ) ;
304+ else return l > 255 ? new types . Ulong ( l ) : new types . SmallUlong ( l ) ;
305+ }
295306} ;
296307types . wrap_uint = function ( l ) {
297308 if ( l === 0 ) return new types . Uint0 ( ) ;
@@ -304,7 +315,15 @@ types.wrap_ubyte = function(l) {
304315 return new types . Ubyte ( l ) ;
305316} ;
306317types . wrap_long = function ( l ) {
307- return l > 127 || l < - 128 ? new types . Long ( l ) : new types . SmallLong ( l ) ;
318+ if ( Buffer . isBuffer ( l ) ) {
319+ var negFlag = ( l [ 0 ] & 0x80 ) !== 0 ;
320+ if ( buffer_zero ( l , 7 , negFlag ) && ( l [ 7 ] & 0x80 ) === ( negFlag ? 0x80 : 0 ) ) {
321+ return new types . SmallLong ( negFlag ? - ( ( l [ 7 ] ^ 0xff ) + 1 ) : l [ 7 ] ) ;
322+ }
323+ return new types . Long ( l ) ;
324+ } else {
325+ return l > 127 || l < - 128 ? new types . Long ( l ) : new types . SmallLong ( l ) ;
326+ }
308327} ;
309328types . wrap_int = function ( l ) {
310329 return l > 127 || l < - 128 ? new types . Int ( l ) : new types . SmallInt ( l ) ;
0 commit comments