/lib/mongodb/bson/binary_parser.js

https://github.com/jsjohnst/node-mongodb-native · JavaScript · 253 lines · 223 code · 20 blank · 10 comment · 83 complexity · 214f0ffc504aeaa1dbe420109d88ccca MD5 · raw file

  1. var sys = require('sys');
  2. //+ Jonas Raoni Soares Silva
  3. //@ http://jsfromhell.com/classes/binary-parser [v1.0]
  4. var chr = String.fromCharCode;
  5. var p = exports.BinaryParser = function( bigEndian, allowExceptions ){
  6. this.bigEndian = bigEndian;
  7. this.allowExceptions = allowExceptions;
  8. };
  9. var Buffer = exports.BinaryParser.Buffer = function( bigEndian, buffer ){
  10. this.bigEndian = bigEndian || 0;
  11. this.buffer = [];
  12. this.setBuffer( buffer );
  13. };
  14. Buffer.prototype.setBuffer = function( data ){
  15. if( data ){
  16. for( var l, i = l = data.length, b = this.buffer = new Array( l ); i; b[l - i] = data.charCodeAt( --i ) );
  17. this.bigEndian && b.reverse();
  18. }
  19. };
  20. Buffer.prototype.hasNeededBits = function( neededBits ){
  21. return this.buffer.length >= -( -neededBits >> 3 );
  22. };
  23. Buffer.prototype.checkBuffer = function( neededBits ){
  24. if( !this.hasNeededBits( neededBits ) )
  25. throw new Error( "checkBuffer::missing bytes" );
  26. };
  27. Buffer.prototype.readBits = function( start, length ){
  28. //shl fix: Henri Torgemane ~1996 (compressed by Jonas Raoni)
  29. function shl( a, b ){
  30. for( ; b--; a = ( ( a %= 0x7fffffff + 1 ) & 0x40000000 ) == 0x40000000 ? a * 2 : ( a - 0x40000000 ) * 2 + 0x7fffffff + 1 );
  31. return a;
  32. }
  33. if( start < 0 || length <= 0 )
  34. return 0;
  35. this.checkBuffer( start + length );
  36. for( var offsetLeft, offsetRight = start % 8, curByte = this.buffer.length - ( start >> 3 ) - 1, lastByte = this.buffer.length + ( -( start + length ) >> 3 ), diff = curByte - lastByte, sum = ( ( this.buffer[ curByte ] >> offsetRight ) & ( ( 1 << ( diff ? 8 - offsetRight : length ) ) - 1 ) ) + ( diff && ( offsetLeft = ( start + length ) % 8 ) ? ( this.buffer[ lastByte++ ] & ( ( 1 << offsetLeft ) - 1 ) ) << ( diff-- << 3 ) - offsetRight : 0 ); diff; sum += shl( this.buffer[ lastByte++ ], ( diff-- << 3 ) - offsetRight ) );
  37. return sum;
  38. };
  39. p.warn = function( msg ){
  40. if( this.allowExceptions )
  41. throw new Error( msg );
  42. return 1;
  43. };
  44. p.decodeFloat = function( data, precisionBits, exponentBits ){
  45. var b = new this.Buffer( this.bigEndian, data );
  46. b.checkBuffer( precisionBits + exponentBits + 1 );
  47. var bias = Math.pow( 2, exponentBits - 1 ) - 1, signal = b.readBits( precisionBits + exponentBits, 1 ), exponent = b.readBits( precisionBits, exponentBits ), significand = 0,
  48. divisor = 2, curByte = b.buffer.length + ( -precisionBits >> 3 ) - 1;
  49. do{
  50. for( var byteValue = b.buffer[ ++curByte ], startBit = precisionBits % 8 || 8, mask = 1 << startBit; mask >>= 1; ( byteValue & mask ) && ( significand += 1 / divisor ), divisor *= 2 );
  51. }while( precisionBits -= startBit );
  52. return exponent == ( bias << 1 ) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : ( 1 + signal * -2 ) * ( exponent || significand ? !exponent ? Math.pow( 2, -bias + 1 ) * significand : Math.pow( 2, exponent - bias ) * ( 1 + significand ) : 0 );
  53. };
  54. p.decodeInt = function( data, bits, signed, forceBigEndian ){
  55. var b = new this.Buffer( this.bigEndian||forceBigEndian, data ), x = b.readBits( 0, bits ), max = Math.pow( 2, bits );
  56. return signed && x >= max / 2 ? x - max : x;
  57. };
  58. p.encodeFloat = function( data, precisionBits, exponentBits ){
  59. var bias = Math.pow( 2, exponentBits - 1 ) - 1, minExp = -bias + 1, maxExp = bias, minUnnormExp = minExp - precisionBits,
  60. status = isNaN( n = parseFloat( data ) ) || n == -Infinity || n == +Infinity ? n : 0,
  61. exp = 0, len = 2 * bias + 1 + precisionBits + 3, bin = new Array( len ),
  62. signal = ( n = status !== 0 ? 0 : n ) < 0, n = Math.abs( n ), intPart = Math.floor( n ), floatPart = n - intPart,
  63. i, lastBit, rounded, j, result;
  64. for( i = len; i; bin[--i] = 0 );
  65. for( i = bias + 2; intPart && i; bin[--i] = intPart % 2, intPart = Math.floor( intPart / 2 ) );
  66. for( i = bias + 1; floatPart > 0 && i; ( bin[++i] = ( ( floatPart *= 2 ) >= 1 ) - 0 ) && --floatPart );
  67. for( i = -1; ++i < len && !bin[i]; );
  68. if( bin[( lastBit = precisionBits - 1 + ( i = ( exp = bias + 1 - i ) >= minExp && exp <= maxExp ? i + 1 : bias + 1 - ( exp = minExp - 1 ) ) ) + 1] ){
  69. if( !( rounded = bin[lastBit] ) ){
  70. for( j = lastBit + 2; !rounded && j < len; rounded = bin[j++] );
  71. }
  72. for( j = lastBit + 1; rounded && --j >= 0; ( bin[j] = !bin[j] - 0 ) && ( rounded = 0 ) );
  73. }
  74. for( i = i - 2 < 0 ? -1 : i - 3; ++i < len && !bin[i]; );
  75. if( ( exp = bias + 1 - i ) >= minExp && exp <= maxExp )
  76. ++i;
  77. else if( exp < minExp ){
  78. exp != bias + 1 - len && exp < minUnnormExp && this.warn( "encodeFloat::float underflow" );
  79. i = bias + 1 - ( exp = minExp - 1 );
  80. }
  81. if( intPart || status !== 0 ){
  82. this.warn( intPart ? "encodeFloat::float overflow" : "encodeFloat::" + status );
  83. exp = maxExp + 1;
  84. i = bias + 2;
  85. if( status == -Infinity )
  86. signal = 1;
  87. else if( isNaN( status ) )
  88. bin[i] = 1;
  89. }
  90. for( n = Math.abs( exp + bias ), j = exponentBits + 1, result = ""; --j; result = ( n % 2 ) + result, n = n >>= 1 );
  91. for( n = 0, j = 0, i = ( result = ( signal ? "1" : "0" ) + result + bin.slice( i, i + precisionBits ).join( "" ) ).length, r = []; i; j = ( j + 1 ) % 8 ){
  92. n += ( 1 << j ) * result.charAt( --i );
  93. if( j == 7 ){
  94. r[r.length] = String.fromCharCode( n );
  95. n = 0;
  96. }
  97. }
  98. r[r.length] = n ? String.fromCharCode( n ) : "";
  99. return ( this.bigEndian ? r.reverse() : r ).join( "" );
  100. };
  101. p.encodeInt = function( data, bits, signed, forceBigEndian ){
  102. var max = Math.pow( 2, bits );
  103. ( data >= max || data < -( max / 2 ) ) && this.warn( "encodeInt::overflow" ) && ( data = 0 );
  104. data < 0 && ( data += max );
  105. for( var r = []; data; r[r.length] = String.fromCharCode( data % 256 ), data = Math.floor( data / 256 ) );
  106. for( bits = -( -bits >> 3 ) - r.length; bits--; r[r.length] = "\0" );
  107. return ( (this.bigEndian||forceBigEndian) ? r.reverse() : r ).join( "" );
  108. };
  109. p.toSmall = function( data ){ return this.decodeInt( data, 8, true ); };
  110. p.fromSmall = function( data ){ return this.encodeInt( data, 8, true ); };
  111. p.toByte = function( data ){ return this.decodeInt( data, 8, false ); };
  112. p.fromByte = function( data ){ return this.encodeInt( data, 8, false ); };
  113. p.toShort = function( data ){ return this.decodeInt( data, 16, true ); };
  114. p.fromShort = function( data ){ return this.encodeInt( data, 16, true ); };
  115. p.toWord = function( data ){ return this.decodeInt( data, 16, false ); };
  116. p.fromWord = function( data ){ return this.encodeInt( data, 16, false ); };
  117. p.toInt = function( data ){ return this.decodeInt( data, 32, true ); };
  118. p.fromInt = function( data ){ return this.encodeInt( data, 32, true ); };
  119. p.toLong = function( data ){ return this.decodeInt( data, 64, true ); };
  120. p.fromLong = function( data ){ return this.encodeInt( data, 64, true ); };
  121. p.toDWord = function( data ){ return this.decodeInt( data, 32, false ); };
  122. p.fromDWord = function( data ){ return this.encodeInt( data, 32, false ); };
  123. p.toQWord = function( data ){ return this.decodeInt( data, 64, true ); };
  124. p.fromQWord = function( data ){ return this.encodeInt( data, 64, true ); };
  125. p.toFloat = function( data ){ return this.decodeFloat( data, 23, 8 ); };
  126. p.fromFloat = function( data ){ return this.encodeFloat( data, 23, 8 ); };
  127. p.toDouble = function( data ){ return this.decodeFloat( data, 52, 11 ); };
  128. p.fromDouble = function( data ){ return this.encodeFloat( data, 52, 11 ); };
  129. // Factor out the encode so it can be shared by add_header and push_int32
  130. p.encode_int32 = function(number) {
  131. var a, b, c, d, unsigned;
  132. unsigned = (number < 0) ? (number + 0x100000000) : number;
  133. a = Math.floor(unsigned / 0xffffff);
  134. unsigned &= 0xffffff;
  135. b = Math.floor(unsigned / 0xffff);
  136. unsigned &= 0xffff;
  137. c = Math.floor(unsigned / 0xff);
  138. unsigned &= 0xff;
  139. d = Math.floor(unsigned);
  140. return chr(a) + chr(b) + chr(c) + chr(d);
  141. };
  142. p.encode_int64 = function(number) {
  143. var a, b, c, d, e, f, g, h, unsigned;
  144. unsigned = (number < 0) ? (number + 0x10000000000000000) : number;
  145. a = Math.floor(unsigned / 0xffffffffffffff);
  146. unsigned &= 0xffffffffffffff;
  147. b = Math.floor(unsigned / 0xffffffffffff);
  148. unsigned &= 0xffffffffffff;
  149. c = Math.floor(unsigned / 0xffffffffff);
  150. unsigned &= 0xffffffffff;
  151. d = Math.floor(unsigned / 0xffffffff);
  152. unsigned &= 0xffffffff;
  153. e = Math.floor(unsigned / 0xffffff);
  154. unsigned &= 0xffffff;
  155. f = Math.floor(unsigned / 0xffff);
  156. unsigned &= 0xffff;
  157. g = Math.floor(unsigned / 0xff);
  158. unsigned &= 0xff;
  159. h = Math.floor(unsigned);
  160. return chr(a) + chr(b) + chr(c) + chr(d) + chr(e) + chr(f) + chr(g) + chr(h);
  161. };
  162. /**
  163. UTF8 methods
  164. **/
  165. // Take a raw binary string and return a utf8 string
  166. p.decode_utf8 = function(a) {
  167. var string = "";
  168. var i = 0;
  169. var c = c1 = c2 = 0;
  170. while ( i < a.length ) {
  171. c = a.charCodeAt(i);
  172. if (c < 128) {
  173. string += String.fromCharCode(c);
  174. i++;
  175. } else if((c > 191) && (c < 224)) {
  176. c2 = a.charCodeAt(i+1);
  177. string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
  178. i += 2;
  179. } else {
  180. c2 = a.charCodeAt(i+1);
  181. c3 = a.charCodeAt(i+2);
  182. string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
  183. i += 3;
  184. }
  185. }
  186. return string;
  187. };
  188. // Encode a cstring correctly
  189. p.encode_cstring = function(s) {
  190. return unescape(encodeURIComponent(s)) + p.fromByte(0);
  191. };
  192. // Take a utf8 string and return a binary string
  193. p.encode_utf8 = function(s) {
  194. var a="";
  195. for (var n=0; n< s.length; n++) {
  196. var c=s.charCodeAt(n);
  197. if (c<128) {
  198. a += String.fromCharCode(c);
  199. } else if ((c>127)&&(c<2048)) {
  200. a += String.fromCharCode( (c>>6) | 192) ;
  201. a += String.fromCharCode( (c&63) | 128);
  202. } else {
  203. a += String.fromCharCode( (c>>12) | 224);
  204. a += String.fromCharCode( ((c>>6) & 63) | 128);
  205. a += String.fromCharCode( (c&63) | 128);
  206. }
  207. }
  208. return a;
  209. };
  210. p.hprint = function(s) {
  211. for (var i=0; i<s.length; i++) {
  212. if (s.charCodeAt(i)<32) {
  213. var number = s.charCodeAt(i) <= 15 ? "0" + s.charCodeAt(i).toString(16) : s.charCodeAt(i).toString(16);
  214. sys.debug(number+' : ');}
  215. else {
  216. var number = s.charCodeAt(i) <= 15 ? "0" + s.charCodeAt(i).toString(16) : s.charCodeAt(i).toString(16);
  217. sys.debug(number+' : '+ s.charAt(i));}
  218. }
  219. };
  220. p.to_byte_array = function(s) {
  221. var array = [];
  222. for (var i=0; i<s.length; i++) {
  223. if (s.charCodeAt(i)<32) {array.push(s.charCodeAt(i));}
  224. else {array.push(s.charCodeAt(i))}
  225. }
  226. sys.puts(array);
  227. }
  228. p.pprint = function(s) {
  229. for (var i=0; i<s.length; i++) {
  230. if (s.charCodeAt(i)<32) {sys.puts(s.charCodeAt(i)+' : ');}
  231. else {sys.puts(s.charCodeAt(i)+' : '+ s.charAt(i));}
  232. }
  233. };