utils.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990
  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. // https://developers.google.com/protocol-buffers/
  4. //
  5. // Redistribution and use in source and binary forms, with or without
  6. // modification, are permitted provided that the following conditions are
  7. // met:
  8. //
  9. // * Redistributions of source code must retain the above copyright
  10. // notice, this list of conditions and the following disclaimer.
  11. // * Redistributions in binary form must reproduce the above
  12. // copyright notice, this list of conditions and the following disclaimer
  13. // in the documentation and/or other materials provided with the
  14. // distribution.
  15. // * Neither the name of Google Inc. nor the names of its
  16. // contributors may be used to endorse or promote products derived from
  17. // this software without specific prior written permission.
  18. //
  19. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. /**
  31. * @fileoverview This file contains helper code used by jspb.BinaryReader
  32. * and BinaryWriter.
  33. *
  34. * @author aappleby@google.com (Austin Appleby)
  35. */
  36. goog.provide('jspb.utils');
  37. goog.require('goog.asserts');
  38. goog.require('goog.crypt');
  39. goog.require('goog.crypt.base64');
  40. goog.require('goog.string');
  41. goog.require('jspb.BinaryConstants');
  42. /**
  43. * Javascript can't natively handle 64-bit data types, so to manipulate them we
  44. * have to split them into two 32-bit halves and do the math manually.
  45. *
  46. * Instead of instantiating and passing small structures around to do this, we
  47. * instead just use two global temporary values. This one stores the low 32
  48. * bits of a split value - for example, if the original value was a 64-bit
  49. * integer, this temporary value will contain the low 32 bits of that integer.
  50. * If the original value was a double, this temporary value will contain the
  51. * low 32 bits of the binary representation of that double, etcetera.
  52. * @type {number}
  53. */
  54. jspb.utils.split64Low = 0;
  55. /**
  56. * And correspondingly, this temporary variable will contain the high 32 bits
  57. * of whatever value was split.
  58. * @type {number}
  59. */
  60. jspb.utils.split64High = 0;
  61. /**
  62. * Splits an unsigned Javascript integer into two 32-bit halves and stores it
  63. * in the temp values above.
  64. * @param {number} value The number to split.
  65. */
  66. jspb.utils.splitUint64 = function(value) {
  67. // Extract low 32 bits and high 32 bits as unsigned integers.
  68. var lowBits = value >>> 0;
  69. var highBits = Math.floor((value - lowBits) /
  70. jspb.BinaryConstants.TWO_TO_32) >>> 0;
  71. jspb.utils.split64Low = lowBits;
  72. jspb.utils.split64High = highBits;
  73. };
  74. /**
  75. * Splits a signed Javascript integer into two 32-bit halves and stores it in
  76. * the temp values above.
  77. * @param {number} value The number to split.
  78. */
  79. jspb.utils.splitInt64 = function(value) {
  80. // Convert to sign-magnitude representation.
  81. var sign = (value < 0);
  82. value = Math.abs(value);
  83. // Extract low 32 bits and high 32 bits as unsigned integers.
  84. var lowBits = value >>> 0;
  85. var highBits = Math.floor((value - lowBits) /
  86. jspb.BinaryConstants.TWO_TO_32);
  87. highBits = highBits >>> 0;
  88. // Perform two's complement conversion if the sign bit was set.
  89. if (sign) {
  90. highBits = ~highBits >>> 0;
  91. lowBits = ~lowBits >>> 0;
  92. lowBits += 1;
  93. if (lowBits > 0xFFFFFFFF) {
  94. lowBits = 0;
  95. highBits++;
  96. if (highBits > 0xFFFFFFFF) highBits = 0;
  97. }
  98. }
  99. jspb.utils.split64Low = lowBits;
  100. jspb.utils.split64High = highBits;
  101. };
  102. /**
  103. * Convers a signed Javascript integer into zigzag format, splits it into two
  104. * 32-bit halves, and stores it in the temp values above.
  105. * @param {number} value The number to split.
  106. */
  107. jspb.utils.splitZigzag64 = function(value) {
  108. // Convert to sign-magnitude and scale by 2 before we split the value.
  109. var sign = (value < 0);
  110. value = Math.abs(value) * 2;
  111. jspb.utils.splitUint64(value);
  112. var lowBits = jspb.utils.split64Low;
  113. var highBits = jspb.utils.split64High;
  114. // If the value is negative, subtract 1 from the split representation so we
  115. // don't lose the sign bit due to precision issues.
  116. if (sign) {
  117. if (lowBits == 0) {
  118. if (highBits == 0) {
  119. lowBits = 0xFFFFFFFF;
  120. highBits = 0xFFFFFFFF;
  121. } else {
  122. highBits--;
  123. lowBits = 0xFFFFFFFF;
  124. }
  125. } else {
  126. lowBits--;
  127. }
  128. }
  129. jspb.utils.split64Low = lowBits;
  130. jspb.utils.split64High = highBits;
  131. };
  132. /**
  133. * Converts a floating-point number into 32-bit IEEE representation and stores
  134. * it in the temp values above.
  135. * @param {number} value
  136. */
  137. jspb.utils.splitFloat32 = function(value) {
  138. var sign = (value < 0) ? 1 : 0;
  139. value = sign ? -value : value;
  140. var exp;
  141. var mant;
  142. // Handle zeros.
  143. if (value === 0) {
  144. if ((1 / value) > 0) {
  145. // Positive zero.
  146. jspb.utils.split64High = 0;
  147. jspb.utils.split64Low = 0x00000000;
  148. } else {
  149. // Negative zero.
  150. jspb.utils.split64High = 0;
  151. jspb.utils.split64Low = 0x80000000;
  152. }
  153. return;
  154. }
  155. // Handle nans.
  156. if (isNaN(value)) {
  157. jspb.utils.split64High = 0;
  158. jspb.utils.split64Low = 0x7FFFFFFF;
  159. return;
  160. }
  161. // Handle infinities.
  162. if (value > jspb.BinaryConstants.FLOAT32_MAX) {
  163. jspb.utils.split64High = 0;
  164. jspb.utils.split64Low = ((sign << 31) | (0x7F800000)) >>> 0;
  165. return;
  166. }
  167. // Handle denormals.
  168. if (value < jspb.BinaryConstants.FLOAT32_MIN) {
  169. // Number is a denormal.
  170. mant = Math.round(value / Math.pow(2, -149));
  171. jspb.utils.split64High = 0;
  172. jspb.utils.split64Low = ((sign << 31) | mant) >>> 0;
  173. return;
  174. }
  175. exp = Math.floor(Math.log(value) / Math.LN2);
  176. mant = value * Math.pow(2, -exp);
  177. mant = Math.round(mant * jspb.BinaryConstants.TWO_TO_23) & 0x7FFFFF;
  178. jspb.utils.split64High = 0;
  179. jspb.utils.split64Low = ((sign << 31) | ((exp + 127) << 23) | mant) >>> 0;
  180. };
  181. /**
  182. * Converts a floating-point number into 64-bit IEEE representation and stores
  183. * it in the temp values above.
  184. * @param {number} value
  185. */
  186. jspb.utils.splitFloat64 = function(value) {
  187. var sign = (value < 0) ? 1 : 0;
  188. value = sign ? -value : value;
  189. // Handle zeros.
  190. if (value === 0) {
  191. if ((1 / value) > 0) {
  192. // Positive zero.
  193. jspb.utils.split64High = 0x00000000;
  194. jspb.utils.split64Low = 0x00000000;
  195. } else {
  196. // Negative zero.
  197. jspb.utils.split64High = 0x80000000;
  198. jspb.utils.split64Low = 0x00000000;
  199. }
  200. return;
  201. }
  202. // Handle nans.
  203. if (isNaN(value)) {
  204. jspb.utils.split64High = 0x7FFFFFFF;
  205. jspb.utils.split64Low = 0xFFFFFFFF;
  206. return;
  207. }
  208. // Handle infinities.
  209. if (value > jspb.BinaryConstants.FLOAT64_MAX) {
  210. jspb.utils.split64High = ((sign << 31) | (0x7FF00000)) >>> 0;
  211. jspb.utils.split64Low = 0;
  212. return;
  213. }
  214. // Handle denormals.
  215. if (value < jspb.BinaryConstants.FLOAT64_MIN) {
  216. // Number is a denormal.
  217. var mant = value / Math.pow(2, -1074);
  218. var mantHigh = (mant / jspb.BinaryConstants.TWO_TO_32);
  219. jspb.utils.split64High = ((sign << 31) | mantHigh) >>> 0;
  220. jspb.utils.split64Low = (mant >>> 0);
  221. return;
  222. }
  223. var exp = Math.floor(Math.log(value) / Math.LN2);
  224. if (exp == 1024) exp = 1023;
  225. var mant = value * Math.pow(2, -exp);
  226. var mantHigh = (mant * jspb.BinaryConstants.TWO_TO_20) & 0xFFFFF;
  227. var mantLow = (mant * jspb.BinaryConstants.TWO_TO_52) >>> 0;
  228. jspb.utils.split64High =
  229. ((sign << 31) | ((exp + 1023) << 20) | mantHigh) >>> 0;
  230. jspb.utils.split64Low = mantLow;
  231. };
  232. /**
  233. * Converts an 8-character hash string into two 32-bit numbers and stores them
  234. * in the temp values above.
  235. * @param {string} hash
  236. */
  237. jspb.utils.splitHash64 = function(hash) {
  238. var a = hash.charCodeAt(0);
  239. var b = hash.charCodeAt(1);
  240. var c = hash.charCodeAt(2);
  241. var d = hash.charCodeAt(3);
  242. var e = hash.charCodeAt(4);
  243. var f = hash.charCodeAt(5);
  244. var g = hash.charCodeAt(6);
  245. var h = hash.charCodeAt(7);
  246. jspb.utils.split64Low = (a + (b << 8) + (c << 16) + (d << 24)) >>> 0;
  247. jspb.utils.split64High = (e + (f << 8) + (g << 16) + (h << 24)) >>> 0;
  248. };
  249. /**
  250. * Joins two 32-bit values into a 64-bit unsigned integer. Precision will be
  251. * lost if the result is greater than 2^52.
  252. * @param {number} bitsLow
  253. * @param {number} bitsHigh
  254. * @return {number}
  255. */
  256. jspb.utils.joinUint64 = function(bitsLow, bitsHigh) {
  257. return bitsHigh * jspb.BinaryConstants.TWO_TO_32 + bitsLow;
  258. };
  259. /**
  260. * Joins two 32-bit values into a 64-bit signed integer. Precision will be lost
  261. * if the result is greater than 2^52.
  262. * @param {number} bitsLow
  263. * @param {number} bitsHigh
  264. * @return {number}
  265. */
  266. jspb.utils.joinInt64 = function(bitsLow, bitsHigh) {
  267. // If the high bit is set, do a manual two's complement conversion.
  268. var sign = (bitsHigh & 0x80000000);
  269. if (sign) {
  270. bitsLow = (~bitsLow + 1) >>> 0;
  271. bitsHigh = ~bitsHigh >>> 0;
  272. if (bitsLow == 0) {
  273. bitsHigh = (bitsHigh + 1) >>> 0;
  274. }
  275. }
  276. var result = jspb.utils.joinUint64(bitsLow, bitsHigh);
  277. return sign ? -result : result;
  278. };
  279. /**
  280. * Joins two 32-bit values into a 64-bit unsigned integer and applies zigzag
  281. * decoding. Precision will be lost if the result is greater than 2^52.
  282. * @param {number} bitsLow
  283. * @param {number} bitsHigh
  284. * @return {number}
  285. */
  286. jspb.utils.joinZigzag64 = function(bitsLow, bitsHigh) {
  287. // Extract the sign bit and shift right by one.
  288. var sign = bitsLow & 1;
  289. bitsLow = ((bitsLow >>> 1) | (bitsHigh << 31)) >>> 0;
  290. bitsHigh = bitsHigh >>> 1;
  291. // Increment the split value if the sign bit was set.
  292. if (sign) {
  293. bitsLow = (bitsLow + 1) >>> 0;
  294. if (bitsLow == 0) {
  295. bitsHigh = (bitsHigh + 1) >>> 0;
  296. }
  297. }
  298. var result = jspb.utils.joinUint64(bitsLow, bitsHigh);
  299. return sign ? -result : result;
  300. };
  301. /**
  302. * Joins two 32-bit values into a 32-bit IEEE floating point number and
  303. * converts it back into a Javascript number.
  304. * @param {number} bitsLow The low 32 bits of the binary number;
  305. * @param {number} bitsHigh The high 32 bits of the binary number.
  306. * @return {number}
  307. */
  308. jspb.utils.joinFloat32 = function(bitsLow, bitsHigh) {
  309. var sign = ((bitsLow >> 31) * 2 + 1);
  310. var exp = (bitsLow >>> 23) & 0xFF;
  311. var mant = bitsLow & 0x7FFFFF;
  312. if (exp == 0xFF) {
  313. if (mant) {
  314. return NaN;
  315. } else {
  316. return sign * Infinity;
  317. }
  318. }
  319. if (exp == 0) {
  320. // Denormal.
  321. return sign * Math.pow(2, -149) * mant;
  322. } else {
  323. return sign * Math.pow(2, exp - 150) *
  324. (mant + Math.pow(2, 23));
  325. }
  326. };
  327. /**
  328. * Joins two 32-bit values into a 64-bit IEEE floating point number and
  329. * converts it back into a Javascript number.
  330. * @param {number} bitsLow The low 32 bits of the binary number;
  331. * @param {number} bitsHigh The high 32 bits of the binary number.
  332. * @return {number}
  333. */
  334. jspb.utils.joinFloat64 = function(bitsLow, bitsHigh) {
  335. var sign = ((bitsHigh >> 31) * 2 + 1);
  336. var exp = (bitsHigh >>> 20) & 0x7FF;
  337. var mant = jspb.BinaryConstants.TWO_TO_32 * (bitsHigh & 0xFFFFF) + bitsLow;
  338. if (exp == 0x7FF) {
  339. if (mant) {
  340. return NaN;
  341. } else {
  342. return sign * Infinity;
  343. }
  344. }
  345. if (exp == 0) {
  346. // Denormal.
  347. return sign * Math.pow(2, -1074) * mant;
  348. } else {
  349. return sign * Math.pow(2, exp - 1075) *
  350. (mant + jspb.BinaryConstants.TWO_TO_52);
  351. }
  352. };
  353. /**
  354. * Joins two 32-bit values into an 8-character hash string.
  355. * @param {number} bitsLow
  356. * @param {number} bitsHigh
  357. * @return {string}
  358. */
  359. jspb.utils.joinHash64 = function(bitsLow, bitsHigh) {
  360. var a = (bitsLow >>> 0) & 0xFF;
  361. var b = (bitsLow >>> 8) & 0xFF;
  362. var c = (bitsLow >>> 16) & 0xFF;
  363. var d = (bitsLow >>> 24) & 0xFF;
  364. var e = (bitsHigh >>> 0) & 0xFF;
  365. var f = (bitsHigh >>> 8) & 0xFF;
  366. var g = (bitsHigh >>> 16) & 0xFF;
  367. var h = (bitsHigh >>> 24) & 0xFF;
  368. return String.fromCharCode(a, b, c, d, e, f, g, h);
  369. };
  370. /**
  371. * Individual digits for number->string conversion.
  372. * @const {!Array<string>}
  373. */
  374. jspb.utils.DIGITS = [
  375. '0', '1', '2', '3', '4', '5', '6', '7',
  376. '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
  377. ];
  378. /**
  379. * Losslessly converts a 64-bit unsigned integer in 32:32 split representation
  380. * into a decimal string.
  381. * @param {number} bitsLow The low 32 bits of the binary number;
  382. * @param {number} bitsHigh The high 32 bits of the binary number.
  383. * @return {string} The binary number represented as a string.
  384. */
  385. jspb.utils.joinUnsignedDecimalString = function(bitsLow, bitsHigh) {
  386. // Skip the expensive conversion if the number is small enough to use the
  387. // built-in conversions.
  388. if (bitsHigh <= 0x1FFFFF) {
  389. return '' + (jspb.BinaryConstants.TWO_TO_32 * bitsHigh + bitsLow);
  390. }
  391. // What this code is doing is essentially converting the input number from
  392. // base-2 to base-1e7, which allows us to represent the 64-bit range with
  393. // only 3 (very large) digits. Those digits are then trivial to convert to
  394. // a base-10 string.
  395. // The magic numbers used here are -
  396. // 2^24 = 16777216 = (1,6777216) in base-1e7.
  397. // 2^48 = 281474976710656 = (2,8147497,6710656) in base-1e7.
  398. // Split 32:32 representation into 16:24:24 representation so our
  399. // intermediate digits don't overflow.
  400. var low = bitsLow & 0xFFFFFF;
  401. var mid = (((bitsLow >>> 24) | (bitsHigh << 8)) >>> 0) & 0xFFFFFF;
  402. var high = (bitsHigh >> 16) & 0xFFFF;
  403. // Assemble our three base-1e7 digits, ignoring carries. The maximum
  404. // value in a digit at this step is representable as a 48-bit integer, which
  405. // can be stored in a 64-bit floating point number.
  406. var digitA = low + (mid * 6777216) + (high * 6710656);
  407. var digitB = mid + (high * 8147497);
  408. var digitC = (high * 2);
  409. // Apply carries from A to B and from B to C.
  410. var base = 10000000;
  411. if (digitA >= base) {
  412. digitB += Math.floor(digitA / base);
  413. digitA %= base;
  414. }
  415. if (digitB >= base) {
  416. digitC += Math.floor(digitB / base);
  417. digitB %= base;
  418. }
  419. // Convert base-1e7 digits to base-10, omitting leading zeroes.
  420. var table = jspb.utils.DIGITS;
  421. var start = false;
  422. var result = '';
  423. function emit(digit) {
  424. var temp = base;
  425. for (var i = 0; i < 7; i++) {
  426. temp /= 10;
  427. var decimalDigit = ((digit / temp) % 10) >>> 0;
  428. if ((decimalDigit == 0) && !start) continue;
  429. start = true;
  430. result += table[decimalDigit];
  431. }
  432. }
  433. if (digitC || start) emit(digitC);
  434. if (digitB || start) emit(digitB);
  435. if (digitA || start) emit(digitA);
  436. return result;
  437. };
  438. /**
  439. * Losslessly converts a 64-bit signed integer in 32:32 split representation
  440. * into a decimal string.
  441. * @param {number} bitsLow The low 32 bits of the binary number;
  442. * @param {number} bitsHigh The high 32 bits of the binary number.
  443. * @return {string} The binary number represented as a string.
  444. */
  445. jspb.utils.joinSignedDecimalString = function(bitsLow, bitsHigh) {
  446. // If we're treating the input as a signed value and the high bit is set, do
  447. // a manual two's complement conversion before the decimal conversion.
  448. var negative = (bitsHigh & 0x80000000);
  449. if (negative) {
  450. bitsLow = (~bitsLow + 1) >>> 0;
  451. var carry = (bitsLow == 0) ? 1 : 0;
  452. bitsHigh = (~bitsHigh + carry) >>> 0;
  453. }
  454. var result = jspb.utils.joinUnsignedDecimalString(bitsLow, bitsHigh);
  455. return negative ? '-' + result : result;
  456. };
  457. /**
  458. * Convert an 8-character hash string representing either a signed or unsigned
  459. * 64-bit integer into its decimal representation without losing accuracy.
  460. * @param {string} hash The hash string to convert.
  461. * @param {boolean} signed True if we should treat the hash string as encoding
  462. * a signed integer.
  463. * @return {string}
  464. */
  465. jspb.utils.hash64ToDecimalString = function(hash, signed) {
  466. jspb.utils.splitHash64(hash);
  467. var bitsLow = jspb.utils.split64Low;
  468. var bitsHigh = jspb.utils.split64High;
  469. return signed ?
  470. jspb.utils.joinSignedDecimalString(bitsLow, bitsHigh) :
  471. jspb.utils.joinUnsignedDecimalString(bitsLow, bitsHigh);
  472. };
  473. /**
  474. * Converts an array of 8-character hash strings into their decimal
  475. * representations.
  476. * @param {!Array<string>} hashes The array of hash strings to convert.
  477. * @param {boolean} signed True if we should treat the hash string as encoding
  478. * a signed integer.
  479. * @return {!Array<string>}
  480. */
  481. jspb.utils.hash64ArrayToDecimalStrings = function(hashes, signed) {
  482. var result = new Array(hashes.length);
  483. for (var i = 0; i < hashes.length; i++) {
  484. result[i] = jspb.utils.hash64ToDecimalString(hashes[i], signed);
  485. }
  486. return result;
  487. };
  488. /**
  489. * Converts a signed or unsigned decimal string into its hash string
  490. * representation.
  491. * @param {string} dec
  492. * @return {string}
  493. */
  494. jspb.utils.decimalStringToHash64 = function(dec) {
  495. goog.asserts.assert(dec.length > 0);
  496. // Check for minus sign.
  497. var minus = false;
  498. if (dec[0] === '-') {
  499. minus = true;
  500. dec = dec.slice(1);
  501. }
  502. // Store result as a byte array.
  503. var resultBytes = [0, 0, 0, 0, 0, 0, 0, 0];
  504. // Set result to m*result + c.
  505. function muladd(m, c) {
  506. for (var i = 0; i < 8 && (m !== 1 || c > 0); i++) {
  507. var r = m * resultBytes[i] + c;
  508. resultBytes[i] = r & 0xFF;
  509. c = r >>> 8;
  510. }
  511. }
  512. // Negate the result bits.
  513. function neg() {
  514. for (var i = 0; i < 8; i++) {
  515. resultBytes[i] = (~resultBytes[i]) & 0xFF;
  516. }
  517. }
  518. // For each decimal digit, set result to 10*result + digit.
  519. for (var i = 0; i < dec.length; i++) {
  520. muladd(10, jspb.utils.DIGITS.indexOf(dec[i]));
  521. }
  522. // If there's a minus sign, convert into two's complement.
  523. if (minus) {
  524. neg();
  525. muladd(1, 1);
  526. }
  527. return goog.crypt.byteArrayToString(resultBytes);
  528. };
  529. /**
  530. * Converts a signed or unsigned decimal string into two 32-bit halves, and
  531. * stores them in the temp variables listed above.
  532. * @param {string} value The decimal string to convert.
  533. */
  534. jspb.utils.splitDecimalString = function(value) {
  535. jspb.utils.splitHash64(jspb.utils.decimalStringToHash64(value));
  536. };
  537. /**
  538. * Converts an 8-character hash string into its hexadecimal representation.
  539. * @param {string} hash
  540. * @return {string}
  541. */
  542. jspb.utils.hash64ToHexString = function(hash) {
  543. var temp = new Array(18);
  544. temp[0] = '0';
  545. temp[1] = 'x';
  546. for (var i = 0; i < 8; i++) {
  547. var c = hash.charCodeAt(7 - i);
  548. temp[i * 2 + 2] = jspb.utils.DIGITS[c >> 4];
  549. temp[i * 2 + 3] = jspb.utils.DIGITS[c & 0xF];
  550. }
  551. var result = temp.join('');
  552. return result;
  553. };
  554. /**
  555. * Converts a '0x<16 digits>' hex string into its hash string representation.
  556. * @param {string} hex
  557. * @return {string}
  558. */
  559. jspb.utils.hexStringToHash64 = function(hex) {
  560. hex = hex.toLowerCase();
  561. goog.asserts.assert(hex.length == 18);
  562. goog.asserts.assert(hex[0] == '0');
  563. goog.asserts.assert(hex[1] == 'x');
  564. var result = '';
  565. for (var i = 0; i < 8; i++) {
  566. var hi = jspb.utils.DIGITS.indexOf(hex[i * 2 + 2]);
  567. var lo = jspb.utils.DIGITS.indexOf(hex[i * 2 + 3]);
  568. result = String.fromCharCode(hi * 16 + lo) + result;
  569. }
  570. return result;
  571. };
  572. /**
  573. * Convert an 8-character hash string representing either a signed or unsigned
  574. * 64-bit integer into a Javascript number. Will lose accuracy if the result is
  575. * larger than 2^52.
  576. * @param {string} hash The hash string to convert.
  577. * @param {boolean} signed True if the has should be interpreted as a signed
  578. * number.
  579. * @return {number}
  580. */
  581. jspb.utils.hash64ToNumber = function(hash, signed) {
  582. jspb.utils.splitHash64(hash);
  583. var bitsLow = jspb.utils.split64Low;
  584. var bitsHigh = jspb.utils.split64High;
  585. return signed ? jspb.utils.joinInt64(bitsLow, bitsHigh) :
  586. jspb.utils.joinUint64(bitsLow, bitsHigh);
  587. };
  588. /**
  589. * Convert a Javascript number into an 8-character hash string. Will lose
  590. * precision if the value is non-integral or greater than 2^64.
  591. * @param {number} value The integer to convert.
  592. * @return {string}
  593. */
  594. jspb.utils.numberToHash64 = function(value) {
  595. jspb.utils.splitInt64(value);
  596. return jspb.utils.joinHash64(jspb.utils.split64Low,
  597. jspb.utils.split64High);
  598. };
  599. /**
  600. * Counts the number of contiguous varints in a buffer.
  601. * @param {!Uint8Array} buffer The buffer to scan.
  602. * @param {number} start The starting point in the buffer to scan.
  603. * @param {number} end The end point in the buffer to scan.
  604. * @return {number} The number of varints in the buffer.
  605. */
  606. jspb.utils.countVarints = function(buffer, start, end) {
  607. // Count how many high bits of each byte were set in the buffer.
  608. var count = 0;
  609. for (var i = start; i < end; i++) {
  610. count += buffer[i] >> 7;
  611. }
  612. // The number of varints in the buffer equals the size of the buffer minus
  613. // the number of non-terminal bytes in the buffer (those with the high bit
  614. // set).
  615. return (end - start) - count;
  616. };
  617. /**
  618. * Counts the number of contiguous varint fields with the given field number in
  619. * the buffer.
  620. * @param {!Uint8Array} buffer The buffer to scan.
  621. * @param {number} start The starting point in the buffer to scan.
  622. * @param {number} end The end point in the buffer to scan.
  623. * @param {number} field The field number to count.
  624. * @return {number} The number of matching fields in the buffer.
  625. */
  626. jspb.utils.countVarintFields = function(buffer, start, end, field) {
  627. var count = 0;
  628. var cursor = start;
  629. var tag = field * 8 + jspb.BinaryConstants.WireType.VARINT;
  630. if (tag < 128) {
  631. // Single-byte field tag, we can use a slightly quicker count.
  632. while (cursor < end) {
  633. // Skip the field tag, or exit if we find a non-matching tag.
  634. if (buffer[cursor++] != tag) return count;
  635. // Field tag matches, we've found a valid field.
  636. count++;
  637. // Skip the varint.
  638. while (1) {
  639. var x = buffer[cursor++];
  640. if ((x & 0x80) == 0) break;
  641. }
  642. }
  643. } else {
  644. while (cursor < end) {
  645. // Skip the field tag, or exit if we find a non-matching tag.
  646. var temp = tag;
  647. while (temp > 128) {
  648. if (buffer[cursor] != ((temp & 0x7F) | 0x80)) return count;
  649. cursor++;
  650. temp >>= 7;
  651. }
  652. if (buffer[cursor++] != temp) return count;
  653. // Field tag matches, we've found a valid field.
  654. count++;
  655. // Skip the varint.
  656. while (1) {
  657. var x = buffer[cursor++];
  658. if ((x & 0x80) == 0) break;
  659. }
  660. }
  661. }
  662. return count;
  663. };
  664. /**
  665. * Counts the number of contiguous fixed32 fields with the given tag in the
  666. * buffer.
  667. * @param {!Uint8Array} buffer The buffer to scan.
  668. * @param {number} start The starting point in the buffer to scan.
  669. * @param {number} end The end point in the buffer to scan.
  670. * @param {number} tag The tag value to count.
  671. * @param {number} stride The number of bytes to skip per field.
  672. * @return {number} The number of fields with a matching tag in the buffer.
  673. * @private
  674. */
  675. jspb.utils.countFixedFields_ =
  676. function(buffer, start, end, tag, stride) {
  677. var count = 0;
  678. var cursor = start;
  679. if (tag < 128) {
  680. // Single-byte field tag, we can use a slightly quicker count.
  681. while (cursor < end) {
  682. // Skip the field tag, or exit if we find a non-matching tag.
  683. if (buffer[cursor++] != tag) return count;
  684. // Field tag matches, we've found a valid field.
  685. count++;
  686. // Skip the value.
  687. cursor += stride;
  688. }
  689. } else {
  690. while (cursor < end) {
  691. // Skip the field tag, or exit if we find a non-matching tag.
  692. var temp = tag;
  693. while (temp > 128) {
  694. if (buffer[cursor++] != ((temp & 0x7F) | 0x80)) return count;
  695. temp >>= 7;
  696. }
  697. if (buffer[cursor++] != temp) return count;
  698. // Field tag matches, we've found a valid field.
  699. count++;
  700. // Skip the value.
  701. cursor += stride;
  702. }
  703. }
  704. return count;
  705. };
  706. /**
  707. * Counts the number of contiguous fixed32 fields with the given field number
  708. * in the buffer.
  709. * @param {!Uint8Array} buffer The buffer to scan.
  710. * @param {number} start The starting point in the buffer to scan.
  711. * @param {number} end The end point in the buffer to scan.
  712. * @param {number} field The field number to count.
  713. * @return {number} The number of matching fields in the buffer.
  714. */
  715. jspb.utils.countFixed32Fields = function(buffer, start, end, field) {
  716. var tag = field * 8 + jspb.BinaryConstants.WireType.FIXED32;
  717. return jspb.utils.countFixedFields_(buffer, start, end, tag, 4);
  718. };
  719. /**
  720. * Counts the number of contiguous fixed64 fields with the given field number
  721. * in the buffer.
  722. * @param {!Uint8Array} buffer The buffer to scan.
  723. * @param {number} start The starting point in the buffer to scan.
  724. * @param {number} end The end point in the buffer to scan.
  725. * @param {number} field The field number to count
  726. * @return {number} The number of matching fields in the buffer.
  727. */
  728. jspb.utils.countFixed64Fields = function(buffer, start, end, field) {
  729. var tag = field * 8 + jspb.BinaryConstants.WireType.FIXED64;
  730. return jspb.utils.countFixedFields_(buffer, start, end, tag, 8);
  731. };
  732. /**
  733. * Counts the number of contiguous delimited fields with the given field number
  734. * in the buffer.
  735. * @param {!Uint8Array} buffer The buffer to scan.
  736. * @param {number} start The starting point in the buffer to scan.
  737. * @param {number} end The end point in the buffer to scan.
  738. * @param {number} field The field number to count.
  739. * @return {number} The number of matching fields in the buffer.
  740. */
  741. jspb.utils.countDelimitedFields = function(buffer, start, end, field) {
  742. var count = 0;
  743. var cursor = start;
  744. var tag = field * 8 + jspb.BinaryConstants.WireType.DELIMITED;
  745. while (cursor < end) {
  746. // Skip the field tag, or exit if we find a non-matching tag.
  747. var temp = tag;
  748. while (temp > 128) {
  749. if (buffer[cursor++] != ((temp & 0x7F) | 0x80)) return count;
  750. temp >>= 7;
  751. }
  752. if (buffer[cursor++] != temp) return count;
  753. // Field tag matches, we've found a valid field.
  754. count++;
  755. // Decode the length prefix.
  756. var length = 0;
  757. var shift = 1;
  758. while (1) {
  759. temp = buffer[cursor++];
  760. length += (temp & 0x7f) * shift;
  761. shift *= 128;
  762. if ((temp & 0x80) == 0) break;
  763. }
  764. // Advance the cursor past the blob.
  765. cursor += length;
  766. }
  767. return count;
  768. };
  769. /**
  770. * String-ify bytes for text format. Should be optimized away in non-debug.
  771. * The returned string uses \xXX escapes for all values and is itself quoted.
  772. * [1, 31] serializes to '"\x01\x1f"'.
  773. * @param {jspb.ByteSource} byteSource The bytes to serialize.
  774. * @return {string} Stringified bytes for text format.
  775. */
  776. jspb.utils.debugBytesToTextFormat = function(byteSource) {
  777. var s = '"';
  778. if (byteSource) {
  779. var bytes = jspb.utils.byteSourceToUint8Array(byteSource);
  780. for (var i = 0; i < bytes.length; i++) {
  781. s += '\\x';
  782. if (bytes[i] < 16) s += '0';
  783. s += bytes[i].toString(16);
  784. }
  785. }
  786. return s + '"';
  787. };
  788. /**
  789. * String-ify a scalar for text format. Should be optimized away in non-debug.
  790. * @param {string|number|boolean} scalar The scalar to stringify.
  791. * @return {string} Stringified scalar for text format.
  792. */
  793. jspb.utils.debugScalarToTextFormat = function(scalar) {
  794. if (goog.isString(scalar)) {
  795. return goog.string.quote(scalar);
  796. } else {
  797. return scalar.toString();
  798. }
  799. };
  800. /**
  801. * Utility function: convert a string with codepoints 0--255 inclusive to a
  802. * Uint8Array. If any codepoints greater than 255 exist in the string, throws an
  803. * exception.
  804. * @param {string} str
  805. * @return {!Uint8Array}
  806. */
  807. jspb.utils.stringToByteArray = function(str) {
  808. var arr = new Uint8Array(str.length);
  809. for (var i = 0; i < str.length; i++) {
  810. var codepoint = str.charCodeAt(i);
  811. if (codepoint > 255) {
  812. throw new Error('Conversion error: string contains codepoint ' +
  813. 'outside of byte range');
  814. }
  815. arr[i] = codepoint;
  816. }
  817. return arr;
  818. };
  819. /**
  820. * Converts any type defined in jspb.ByteSource into a Uint8Array.
  821. * @param {!jspb.ByteSource} data
  822. * @return {!Uint8Array}
  823. * @suppress {invalidCasts}
  824. */
  825. jspb.utils.byteSourceToUint8Array = function(data) {
  826. if (data.constructor === Uint8Array) {
  827. return /** @type {!Uint8Array} */(data);
  828. }
  829. if (data.constructor === ArrayBuffer) {
  830. data = /** @type {!ArrayBuffer} */(data);
  831. return /** @type {!Uint8Array} */(new Uint8Array(data));
  832. }
  833. if (data.constructor === Buffer) {
  834. return /** @type {!Uint8Array} */(new Uint8Array(data));
  835. }
  836. if (data.constructor === Array) {
  837. data = /** @type {!Array<number>} */(data);
  838. return /** @type {!Uint8Array} */(new Uint8Array(data));
  839. }
  840. if (data.constructor === String) {
  841. data = /** @type {string} */(data);
  842. return goog.crypt.base64.decodeStringToUint8Array(data);
  843. }
  844. goog.asserts.fail('Type not convertible to Uint8Array.');
  845. return /** @type {!Uint8Array} */(new Uint8Array(0));
  846. };