utils.js 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066
  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. // Compute the least significant exponent needed to represent the magnitude of
  224. // the value by repeadly dividing/multiplying by 2 until the magnitude
  225. // crosses 2. While tempting to use log math to find the exponent, at the
  226. // bounadaries of precision, the result can be off by one.
  227. var maxDoubleExponent = 1023;
  228. var minDoubleExponent = -1022;
  229. var x = value;
  230. var exp = 0;
  231. if (x >= 2) {
  232. while (x >= 2 && exp < maxDoubleExponent) {
  233. exp++;
  234. x = x / 2;
  235. }
  236. } else {
  237. while (x < 1 && exp > minDoubleExponent) {
  238. x = x * 2;
  239. exp--;
  240. }
  241. }
  242. var mant = value * Math.pow(2, -exp);
  243. var mantHigh = (mant * jspb.BinaryConstants.TWO_TO_20) & 0xFFFFF;
  244. var mantLow = (mant * jspb.BinaryConstants.TWO_TO_52) >>> 0;
  245. jspb.utils.split64High =
  246. ((sign << 31) | ((exp + 1023) << 20) | mantHigh) >>> 0;
  247. jspb.utils.split64Low = mantLow;
  248. };
  249. /**
  250. * Converts an 8-character hash string into two 32-bit numbers and stores them
  251. * in the temp values above.
  252. * @param {string} hash
  253. */
  254. jspb.utils.splitHash64 = function(hash) {
  255. var a = hash.charCodeAt(0);
  256. var b = hash.charCodeAt(1);
  257. var c = hash.charCodeAt(2);
  258. var d = hash.charCodeAt(3);
  259. var e = hash.charCodeAt(4);
  260. var f = hash.charCodeAt(5);
  261. var g = hash.charCodeAt(6);
  262. var h = hash.charCodeAt(7);
  263. jspb.utils.split64Low = (a + (b << 8) + (c << 16) + (d << 24)) >>> 0;
  264. jspb.utils.split64High = (e + (f << 8) + (g << 16) + (h << 24)) >>> 0;
  265. };
  266. /**
  267. * Joins two 32-bit values into a 64-bit unsigned integer. Precision will be
  268. * lost if the result is greater than 2^52.
  269. * @param {number} bitsLow
  270. * @param {number} bitsHigh
  271. * @return {number}
  272. */
  273. jspb.utils.joinUint64 = function(bitsLow, bitsHigh) {
  274. return bitsHigh * jspb.BinaryConstants.TWO_TO_32 + (bitsLow >>> 0);
  275. };
  276. /**
  277. * Joins two 32-bit values into a 64-bit signed integer. Precision will be lost
  278. * if the result is greater than 2^52.
  279. * @param {number} bitsLow
  280. * @param {number} bitsHigh
  281. * @return {number}
  282. */
  283. jspb.utils.joinInt64 = function(bitsLow, bitsHigh) {
  284. // If the high bit is set, do a manual two's complement conversion.
  285. var sign = (bitsHigh & 0x80000000);
  286. if (sign) {
  287. bitsLow = (~bitsLow + 1) >>> 0;
  288. bitsHigh = ~bitsHigh >>> 0;
  289. if (bitsLow == 0) {
  290. bitsHigh = (bitsHigh + 1) >>> 0;
  291. }
  292. }
  293. var result = jspb.utils.joinUint64(bitsLow, bitsHigh);
  294. return sign ? -result : result;
  295. };
  296. /**
  297. * Converts split 64-bit values from standard two's complement encoding to
  298. * zig-zag encoding. Invokes the provided function to produce final result.
  299. *
  300. * @param {number} bitsLow
  301. * @param {number} bitsHigh
  302. * @param {function(number, number): T} convert Conversion function to produce
  303. * the result value, takes parameters (lowBits, highBits).
  304. * @return {T}
  305. * @template T
  306. */
  307. jspb.utils.toZigzag64 = function(bitsLow, bitsHigh, convert) {
  308. // See
  309. // https://engdoc.corp.google.com/eng/howto/protocolbuffers/developerguide/encoding.shtml?cl=head#types
  310. // 64-bit math is: (n << 1) ^ (n >> 63)
  311. //
  312. // To do this in 32 bits, we can get a 32-bit sign-flipping mask from the
  313. // high word.
  314. // Then we can operate on each word individually, with the addition of the
  315. // "carry" to get the most significant bit from the low word into the high
  316. // word.
  317. var signFlipMask = bitsHigh >> 31;
  318. bitsHigh = (bitsHigh << 1 | bitsLow >>> 31) ^ signFlipMask;
  319. bitsLow = (bitsLow << 1) ^ signFlipMask;
  320. return convert(bitsLow, bitsHigh);
  321. };
  322. /**
  323. * Joins two 32-bit values into a 64-bit unsigned integer and applies zigzag
  324. * decoding. Precision will be lost if the result is greater than 2^52.
  325. * @param {number} bitsLow
  326. * @param {number} bitsHigh
  327. * @return {number}
  328. */
  329. jspb.utils.joinZigzag64 = function(bitsLow, bitsHigh) {
  330. return jspb.utils.fromZigzag64(bitsLow, bitsHigh, jspb.utils.joinInt64);
  331. };
  332. /**
  333. * Converts split 64-bit values from zigzag encoding to standard two's
  334. * complement encoding. Invokes the provided function to produce final result.
  335. *
  336. * @param {number} bitsLow
  337. * @param {number} bitsHigh
  338. * @param {function(number, number): T} convert Conversion function to produce
  339. * the result value, takes parameters (lowBits, highBits).
  340. * @return {T}
  341. * @template T
  342. */
  343. jspb.utils.fromZigzag64 = function(bitsLow, bitsHigh, convert) {
  344. // 64 bit math is:
  345. // signmask = (zigzag & 1) ? -1 : 0;
  346. // twosComplement = (zigzag >> 1) ^ signmask;
  347. //
  348. // To work with 32 bit, we can operate on both but "carry" the lowest bit
  349. // from the high word by shifting it up 31 bits to be the most significant bit
  350. // of the low word.
  351. var signFlipMask = -(bitsLow & 1);
  352. bitsLow = ((bitsLow >>> 1) | (bitsHigh << 31)) ^ signFlipMask;
  353. bitsHigh = (bitsHigh >>> 1) ^ signFlipMask;
  354. return convert(bitsLow, bitsHigh);
  355. };
  356. /**
  357. * Joins two 32-bit values into a 32-bit IEEE floating point number and
  358. * converts it back into a Javascript number.
  359. * @param {number} bitsLow The low 32 bits of the binary number;
  360. * @param {number} bitsHigh The high 32 bits of the binary number.
  361. * @return {number}
  362. */
  363. jspb.utils.joinFloat32 = function(bitsLow, bitsHigh) {
  364. var sign = ((bitsLow >> 31) * 2 + 1);
  365. var exp = (bitsLow >>> 23) & 0xFF;
  366. var mant = bitsLow & 0x7FFFFF;
  367. if (exp == 0xFF) {
  368. if (mant) {
  369. return NaN;
  370. } else {
  371. return sign * Infinity;
  372. }
  373. }
  374. if (exp == 0) {
  375. // Denormal.
  376. return sign * Math.pow(2, -149) * mant;
  377. } else {
  378. return sign * Math.pow(2, exp - 150) *
  379. (mant + Math.pow(2, 23));
  380. }
  381. };
  382. /**
  383. * Joins two 32-bit values into a 64-bit IEEE floating point number and
  384. * converts it back into a Javascript number.
  385. * @param {number} bitsLow The low 32 bits of the binary number;
  386. * @param {number} bitsHigh The high 32 bits of the binary number.
  387. * @return {number}
  388. */
  389. jspb.utils.joinFloat64 = function(bitsLow, bitsHigh) {
  390. var sign = ((bitsHigh >> 31) * 2 + 1);
  391. var exp = (bitsHigh >>> 20) & 0x7FF;
  392. var mant = jspb.BinaryConstants.TWO_TO_32 * (bitsHigh & 0xFFFFF) + bitsLow;
  393. if (exp == 0x7FF) {
  394. if (mant) {
  395. return NaN;
  396. } else {
  397. return sign * Infinity;
  398. }
  399. }
  400. if (exp == 0) {
  401. // Denormal.
  402. return sign * Math.pow(2, -1074) * mant;
  403. } else {
  404. return sign * Math.pow(2, exp - 1075) *
  405. (mant + jspb.BinaryConstants.TWO_TO_52);
  406. }
  407. };
  408. /**
  409. * Joins two 32-bit values into an 8-character hash string.
  410. * @param {number} bitsLow
  411. * @param {number} bitsHigh
  412. * @return {string}
  413. */
  414. jspb.utils.joinHash64 = function(bitsLow, bitsHigh) {
  415. var a = (bitsLow >>> 0) & 0xFF;
  416. var b = (bitsLow >>> 8) & 0xFF;
  417. var c = (bitsLow >>> 16) & 0xFF;
  418. var d = (bitsLow >>> 24) & 0xFF;
  419. var e = (bitsHigh >>> 0) & 0xFF;
  420. var f = (bitsHigh >>> 8) & 0xFF;
  421. var g = (bitsHigh >>> 16) & 0xFF;
  422. var h = (bitsHigh >>> 24) & 0xFF;
  423. return String.fromCharCode(a, b, c, d, e, f, g, h);
  424. };
  425. /**
  426. * Individual digits for number->string conversion.
  427. * @const {!Array<string>}
  428. */
  429. jspb.utils.DIGITS = [
  430. '0', '1', '2', '3', '4', '5', '6', '7',
  431. '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
  432. ];
  433. /** @const @private {number} '0' */
  434. jspb.utils.ZERO_CHAR_CODE_ = 48;
  435. /** @const @private {number} 'a' */
  436. jspb.utils.A_CHAR_CODE_ = 97;
  437. /**
  438. * Losslessly converts a 64-bit unsigned integer in 32:32 split representation
  439. * into a decimal string.
  440. * @param {number} bitsLow The low 32 bits of the binary number;
  441. * @param {number} bitsHigh The high 32 bits of the binary number.
  442. * @return {string} The binary number represented as a string.
  443. */
  444. jspb.utils.joinUnsignedDecimalString = function(bitsLow, bitsHigh) {
  445. // Skip the expensive conversion if the number is small enough to use the
  446. // built-in conversions.
  447. if (bitsHigh <= 0x1FFFFF) {
  448. return '' + (jspb.BinaryConstants.TWO_TO_32 * bitsHigh + bitsLow);
  449. }
  450. // What this code is doing is essentially converting the input number from
  451. // base-2 to base-1e7, which allows us to represent the 64-bit range with
  452. // only 3 (very large) digits. Those digits are then trivial to convert to
  453. // a base-10 string.
  454. // The magic numbers used here are -
  455. // 2^24 = 16777216 = (1,6777216) in base-1e7.
  456. // 2^48 = 281474976710656 = (2,8147497,6710656) in base-1e7.
  457. // Split 32:32 representation into 16:24:24 representation so our
  458. // intermediate digits don't overflow.
  459. var low = bitsLow & 0xFFFFFF;
  460. var mid = (((bitsLow >>> 24) | (bitsHigh << 8)) >>> 0) & 0xFFFFFF;
  461. var high = (bitsHigh >> 16) & 0xFFFF;
  462. // Assemble our three base-1e7 digits, ignoring carries. The maximum
  463. // value in a digit at this step is representable as a 48-bit integer, which
  464. // can be stored in a 64-bit floating point number.
  465. var digitA = low + (mid * 6777216) + (high * 6710656);
  466. var digitB = mid + (high * 8147497);
  467. var digitC = (high * 2);
  468. // Apply carries from A to B and from B to C.
  469. var base = 10000000;
  470. if (digitA >= base) {
  471. digitB += Math.floor(digitA / base);
  472. digitA %= base;
  473. }
  474. if (digitB >= base) {
  475. digitC += Math.floor(digitB / base);
  476. digitB %= base;
  477. }
  478. // Convert base-1e7 digits to base-10, with optional leading zeroes.
  479. function decimalFrom1e7(digit1e7, needLeadingZeros) {
  480. var partial = digit1e7 ? String(digit1e7) : '';
  481. if (needLeadingZeros) {
  482. return '0000000'.slice(partial.length) + partial;
  483. }
  484. return partial;
  485. }
  486. return decimalFrom1e7(digitC, /*needLeadingZeros=*/ 0) +
  487. decimalFrom1e7(digitB, /*needLeadingZeros=*/ digitC) +
  488. // If the final 1e7 digit didn't need leading zeros, we would have
  489. // returned via the trivial code path at the top.
  490. decimalFrom1e7(digitA, /*needLeadingZeros=*/ 1);
  491. };
  492. /**
  493. * Losslessly converts a 64-bit signed integer in 32:32 split representation
  494. * into a decimal string.
  495. * @param {number} bitsLow The low 32 bits of the binary number;
  496. * @param {number} bitsHigh The high 32 bits of the binary number.
  497. * @return {string} The binary number represented as a string.
  498. */
  499. jspb.utils.joinSignedDecimalString = function(bitsLow, bitsHigh) {
  500. // If we're treating the input as a signed value and the high bit is set, do
  501. // a manual two's complement conversion before the decimal conversion.
  502. var negative = (bitsHigh & 0x80000000);
  503. if (negative) {
  504. bitsLow = (~bitsLow + 1) >>> 0;
  505. var carry = (bitsLow == 0) ? 1 : 0;
  506. bitsHigh = (~bitsHigh + carry) >>> 0;
  507. }
  508. var result = jspb.utils.joinUnsignedDecimalString(bitsLow, bitsHigh);
  509. return negative ? '-' + result : result;
  510. };
  511. /**
  512. * Convert an 8-character hash string representing either a signed or unsigned
  513. * 64-bit integer into its decimal representation without losing accuracy.
  514. * @param {string} hash The hash string to convert.
  515. * @param {boolean} signed True if we should treat the hash string as encoding
  516. * a signed integer.
  517. * @return {string}
  518. */
  519. jspb.utils.hash64ToDecimalString = function(hash, signed) {
  520. jspb.utils.splitHash64(hash);
  521. var bitsLow = jspb.utils.split64Low;
  522. var bitsHigh = jspb.utils.split64High;
  523. return signed ?
  524. jspb.utils.joinSignedDecimalString(bitsLow, bitsHigh) :
  525. jspb.utils.joinUnsignedDecimalString(bitsLow, bitsHigh);
  526. };
  527. /**
  528. * Converts an array of 8-character hash strings into their decimal
  529. * representations.
  530. * @param {!Array<string>} hashes The array of hash strings to convert.
  531. * @param {boolean} signed True if we should treat the hash string as encoding
  532. * a signed integer.
  533. * @return {!Array<string>}
  534. */
  535. jspb.utils.hash64ArrayToDecimalStrings = function(hashes, signed) {
  536. var result = new Array(hashes.length);
  537. for (var i = 0; i < hashes.length; i++) {
  538. result[i] = jspb.utils.hash64ToDecimalString(hashes[i], signed);
  539. }
  540. return result;
  541. };
  542. /**
  543. * Converts a signed or unsigned decimal string into its hash string
  544. * representation.
  545. * @param {string} dec
  546. * @return {string}
  547. */
  548. jspb.utils.decimalStringToHash64 = function(dec) {
  549. goog.asserts.assert(dec.length > 0);
  550. // Check for minus sign.
  551. var minus = false;
  552. if (dec[0] === '-') {
  553. minus = true;
  554. dec = dec.slice(1);
  555. }
  556. // Store result as a byte array.
  557. var resultBytes = [0, 0, 0, 0, 0, 0, 0, 0];
  558. // Set result to m*result + c.
  559. function muladd(m, c) {
  560. for (var i = 0; i < 8 && (m !== 1 || c > 0); i++) {
  561. var r = m * resultBytes[i] + c;
  562. resultBytes[i] = r & 0xFF;
  563. c = r >>> 8;
  564. }
  565. }
  566. // Negate the result bits.
  567. function neg() {
  568. for (var i = 0; i < 8; i++) {
  569. resultBytes[i] = (~resultBytes[i]) & 0xFF;
  570. }
  571. }
  572. // For each decimal digit, set result to 10*result + digit.
  573. for (var i = 0; i < dec.length; i++) {
  574. muladd(10, dec.charCodeAt(i) - jspb.utils.ZERO_CHAR_CODE_);
  575. }
  576. // If there's a minus sign, convert into two's complement.
  577. if (minus) {
  578. neg();
  579. muladd(1, 1);
  580. }
  581. return goog.crypt.byteArrayToString(resultBytes);
  582. };
  583. /**
  584. * Converts a signed or unsigned decimal string into two 32-bit halves, and
  585. * stores them in the temp variables listed above.
  586. * @param {string} value The decimal string to convert.
  587. */
  588. jspb.utils.splitDecimalString = function(value) {
  589. jspb.utils.splitHash64(jspb.utils.decimalStringToHash64(value));
  590. };
  591. /**
  592. * @param {number} nibble A 4-bit integer.
  593. * @return {string}
  594. * @private
  595. */
  596. jspb.utils.toHexDigit_ = function(nibble) {
  597. return String.fromCharCode(
  598. nibble < 10 ? jspb.utils.ZERO_CHAR_CODE_ + nibble :
  599. jspb.utils.A_CHAR_CODE_ - 10 + nibble);
  600. };
  601. /**
  602. * @param {number} hexCharCode
  603. * @return {number}
  604. * @private
  605. */
  606. jspb.utils.fromHexCharCode_ = function(hexCharCode) {
  607. if (hexCharCode >= jspb.utils.A_CHAR_CODE_) {
  608. return hexCharCode - jspb.utils.A_CHAR_CODE_ + 10;
  609. }
  610. return hexCharCode - jspb.utils.ZERO_CHAR_CODE_;
  611. };
  612. /**
  613. * Converts an 8-character hash string into its hexadecimal representation.
  614. * @param {string} hash
  615. * @return {string}
  616. */
  617. jspb.utils.hash64ToHexString = function(hash) {
  618. var temp = new Array(18);
  619. temp[0] = '0';
  620. temp[1] = 'x';
  621. for (var i = 0; i < 8; i++) {
  622. var c = hash.charCodeAt(7 - i);
  623. temp[i * 2 + 2] = jspb.utils.toHexDigit_(c >> 4);
  624. temp[i * 2 + 3] = jspb.utils.toHexDigit_(c & 0xF);
  625. }
  626. var result = temp.join('');
  627. return result;
  628. };
  629. /**
  630. * Converts a '0x<16 digits>' hex string into its hash string representation.
  631. * @param {string} hex
  632. * @return {string}
  633. */
  634. jspb.utils.hexStringToHash64 = function(hex) {
  635. hex = hex.toLowerCase();
  636. goog.asserts.assert(hex.length == 18);
  637. goog.asserts.assert(hex[0] == '0');
  638. goog.asserts.assert(hex[1] == 'x');
  639. var result = '';
  640. for (var i = 0; i < 8; i++) {
  641. var hi = jspb.utils.fromHexCharCode_(hex.charCodeAt(i * 2 + 2));
  642. var lo = jspb.utils.fromHexCharCode_(hex.charCodeAt(i * 2 + 3));
  643. result = String.fromCharCode(hi * 16 + lo) + result;
  644. }
  645. return result;
  646. };
  647. /**
  648. * Convert an 8-character hash string representing either a signed or unsigned
  649. * 64-bit integer into a Javascript number. Will lose accuracy if the result is
  650. * larger than 2^52.
  651. * @param {string} hash The hash string to convert.
  652. * @param {boolean} signed True if the has should be interpreted as a signed
  653. * number.
  654. * @return {number}
  655. */
  656. jspb.utils.hash64ToNumber = function(hash, signed) {
  657. jspb.utils.splitHash64(hash);
  658. var bitsLow = jspb.utils.split64Low;
  659. var bitsHigh = jspb.utils.split64High;
  660. return signed ? jspb.utils.joinInt64(bitsLow, bitsHigh) :
  661. jspb.utils.joinUint64(bitsLow, bitsHigh);
  662. };
  663. /**
  664. * Convert a Javascript number into an 8-character hash string. Will lose
  665. * precision if the value is non-integral or greater than 2^64.
  666. * @param {number} value The integer to convert.
  667. * @return {string}
  668. */
  669. jspb.utils.numberToHash64 = function(value) {
  670. jspb.utils.splitInt64(value);
  671. return jspb.utils.joinHash64(jspb.utils.split64Low,
  672. jspb.utils.split64High);
  673. };
  674. /**
  675. * Counts the number of contiguous varints in a buffer.
  676. * @param {!Uint8Array} buffer The buffer to scan.
  677. * @param {number} start The starting point in the buffer to scan.
  678. * @param {number} end The end point in the buffer to scan.
  679. * @return {number} The number of varints in the buffer.
  680. */
  681. jspb.utils.countVarints = function(buffer, start, end) {
  682. // Count how many high bits of each byte were set in the buffer.
  683. var count = 0;
  684. for (var i = start; i < end; i++) {
  685. count += buffer[i] >> 7;
  686. }
  687. // The number of varints in the buffer equals the size of the buffer minus
  688. // the number of non-terminal bytes in the buffer (those with the high bit
  689. // set).
  690. return (end - start) - count;
  691. };
  692. /**
  693. * Counts the number of contiguous varint fields with the given field number in
  694. * the buffer.
  695. * @param {!Uint8Array} buffer The buffer to scan.
  696. * @param {number} start The starting point in the buffer to scan.
  697. * @param {number} end The end point in the buffer to scan.
  698. * @param {number} field The field number to count.
  699. * @return {number} The number of matching fields in the buffer.
  700. */
  701. jspb.utils.countVarintFields = function(buffer, start, end, field) {
  702. var count = 0;
  703. var cursor = start;
  704. var tag = field * 8 + jspb.BinaryConstants.WireType.VARINT;
  705. if (tag < 128) {
  706. // Single-byte field tag, we can use a slightly quicker count.
  707. while (cursor < end) {
  708. // Skip the field tag, or exit if we find a non-matching tag.
  709. if (buffer[cursor++] != tag) return count;
  710. // Field tag matches, we've found a valid field.
  711. count++;
  712. // Skip the varint.
  713. while (1) {
  714. var x = buffer[cursor++];
  715. if ((x & 0x80) == 0) break;
  716. }
  717. }
  718. } else {
  719. while (cursor < end) {
  720. // Skip the field tag, or exit if we find a non-matching tag.
  721. var temp = tag;
  722. while (temp > 128) {
  723. if (buffer[cursor] != ((temp & 0x7F) | 0x80)) return count;
  724. cursor++;
  725. temp >>= 7;
  726. }
  727. if (buffer[cursor++] != temp) return count;
  728. // Field tag matches, we've found a valid field.
  729. count++;
  730. // Skip the varint.
  731. while (1) {
  732. var x = buffer[cursor++];
  733. if ((x & 0x80) == 0) break;
  734. }
  735. }
  736. }
  737. return count;
  738. };
  739. /**
  740. * Counts the number of contiguous fixed32 fields with the given tag in the
  741. * buffer.
  742. * @param {!Uint8Array} buffer The buffer to scan.
  743. * @param {number} start The starting point in the buffer to scan.
  744. * @param {number} end The end point in the buffer to scan.
  745. * @param {number} tag The tag value to count.
  746. * @param {number} stride The number of bytes to skip per field.
  747. * @return {number} The number of fields with a matching tag in the buffer.
  748. * @private
  749. */
  750. jspb.utils.countFixedFields_ =
  751. function(buffer, start, end, tag, stride) {
  752. var count = 0;
  753. var cursor = start;
  754. if (tag < 128) {
  755. // Single-byte field tag, we can use a slightly quicker count.
  756. while (cursor < end) {
  757. // Skip the field tag, or exit if we find a non-matching tag.
  758. if (buffer[cursor++] != tag) return count;
  759. // Field tag matches, we've found a valid field.
  760. count++;
  761. // Skip the value.
  762. cursor += stride;
  763. }
  764. } else {
  765. while (cursor < end) {
  766. // Skip the field tag, or exit if we find a non-matching tag.
  767. var temp = tag;
  768. while (temp > 128) {
  769. if (buffer[cursor++] != ((temp & 0x7F) | 0x80)) return count;
  770. temp >>= 7;
  771. }
  772. if (buffer[cursor++] != temp) return count;
  773. // Field tag matches, we've found a valid field.
  774. count++;
  775. // Skip the value.
  776. cursor += stride;
  777. }
  778. }
  779. return count;
  780. };
  781. /**
  782. * Counts the number of contiguous fixed32 fields with the given field number
  783. * in the buffer.
  784. * @param {!Uint8Array} buffer The buffer to scan.
  785. * @param {number} start The starting point in the buffer to scan.
  786. * @param {number} end The end point in the buffer to scan.
  787. * @param {number} field The field number to count.
  788. * @return {number} The number of matching fields in the buffer.
  789. */
  790. jspb.utils.countFixed32Fields = function(buffer, start, end, field) {
  791. var tag = field * 8 + jspb.BinaryConstants.WireType.FIXED32;
  792. return jspb.utils.countFixedFields_(buffer, start, end, tag, 4);
  793. };
  794. /**
  795. * Counts the number of contiguous fixed64 fields with the given field number
  796. * in the buffer.
  797. * @param {!Uint8Array} buffer The buffer to scan.
  798. * @param {number} start The starting point in the buffer to scan.
  799. * @param {number} end The end point in the buffer to scan.
  800. * @param {number} field The field number to count
  801. * @return {number} The number of matching fields in the buffer.
  802. */
  803. jspb.utils.countFixed64Fields = function(buffer, start, end, field) {
  804. var tag = field * 8 + jspb.BinaryConstants.WireType.FIXED64;
  805. return jspb.utils.countFixedFields_(buffer, start, end, tag, 8);
  806. };
  807. /**
  808. * Counts the number of contiguous delimited fields with the given field number
  809. * in the buffer.
  810. * @param {!Uint8Array} buffer The buffer to scan.
  811. * @param {number} start The starting point in the buffer to scan.
  812. * @param {number} end The end point in the buffer to scan.
  813. * @param {number} field The field number to count.
  814. * @return {number} The number of matching fields in the buffer.
  815. */
  816. jspb.utils.countDelimitedFields = function(buffer, start, end, field) {
  817. var count = 0;
  818. var cursor = start;
  819. var tag = field * 8 + jspb.BinaryConstants.WireType.DELIMITED;
  820. while (cursor < end) {
  821. // Skip the field tag, or exit if we find a non-matching tag.
  822. var temp = tag;
  823. while (temp > 128) {
  824. if (buffer[cursor++] != ((temp & 0x7F) | 0x80)) return count;
  825. temp >>= 7;
  826. }
  827. if (buffer[cursor++] != temp) return count;
  828. // Field tag matches, we've found a valid field.
  829. count++;
  830. // Decode the length prefix.
  831. var length = 0;
  832. var shift = 1;
  833. while (1) {
  834. temp = buffer[cursor++];
  835. length += (temp & 0x7f) * shift;
  836. shift *= 128;
  837. if ((temp & 0x80) == 0) break;
  838. }
  839. // Advance the cursor past the blob.
  840. cursor += length;
  841. }
  842. return count;
  843. };
  844. /**
  845. * String-ify bytes for text format. Should be optimized away in non-debug.
  846. * The returned string uses \xXX escapes for all values and is itself quoted.
  847. * [1, 31] serializes to '"\x01\x1f"'.
  848. * @param {jspb.ByteSource} byteSource The bytes to serialize.
  849. * @return {string} Stringified bytes for text format.
  850. */
  851. jspb.utils.debugBytesToTextFormat = function(byteSource) {
  852. var s = '"';
  853. if (byteSource) {
  854. var bytes = jspb.utils.byteSourceToUint8Array(byteSource);
  855. for (var i = 0; i < bytes.length; i++) {
  856. s += '\\x';
  857. if (bytes[i] < 16) s += '0';
  858. s += bytes[i].toString(16);
  859. }
  860. }
  861. return s + '"';
  862. };
  863. /**
  864. * String-ify a scalar for text format. Should be optimized away in non-debug.
  865. * @param {string|number|boolean} scalar The scalar to stringify.
  866. * @return {string} Stringified scalar for text format.
  867. */
  868. jspb.utils.debugScalarToTextFormat = function(scalar) {
  869. if (typeof scalar === 'string') {
  870. return goog.string.quote(scalar);
  871. } else {
  872. return scalar.toString();
  873. }
  874. };
  875. /**
  876. * Utility function: convert a string with codepoints 0--255 inclusive to a
  877. * Uint8Array. If any codepoints greater than 255 exist in the string, throws an
  878. * exception.
  879. * @param {string} str
  880. * @return {!Uint8Array}
  881. */
  882. jspb.utils.stringToByteArray = function(str) {
  883. var arr = new Uint8Array(str.length);
  884. for (var i = 0; i < str.length; i++) {
  885. var codepoint = str.charCodeAt(i);
  886. if (codepoint > 255) {
  887. throw new Error('Conversion error: string contains codepoint ' +
  888. 'outside of byte range');
  889. }
  890. arr[i] = codepoint;
  891. }
  892. return arr;
  893. };
  894. /**
  895. * Converts any type defined in jspb.ByteSource into a Uint8Array.
  896. * @param {!jspb.ByteSource} data
  897. * @return {!Uint8Array}
  898. * @suppress {invalidCasts}
  899. */
  900. jspb.utils.byteSourceToUint8Array = function(data) {
  901. if (data.constructor === Uint8Array) {
  902. return /** @type {!Uint8Array} */(data);
  903. }
  904. if (data.constructor === ArrayBuffer) {
  905. data = /** @type {!ArrayBuffer} */(data);
  906. return /** @type {!Uint8Array} */(new Uint8Array(data));
  907. }
  908. if (typeof Buffer != 'undefined' && data.constructor === Buffer) {
  909. return /** @type {!Uint8Array} */ (
  910. new Uint8Array(/** @type {?} */ (data)));
  911. }
  912. if (data.constructor === Array) {
  913. data = /** @type {!Array<number>} */(data);
  914. return /** @type {!Uint8Array} */(new Uint8Array(data));
  915. }
  916. if (data.constructor === String) {
  917. data = /** @type {string} */(data);
  918. return goog.crypt.base64.decodeStringToUint8Array(data);
  919. }
  920. goog.asserts.fail('Type not convertible to Uint8Array.');
  921. return /** @type {!Uint8Array} */(new Uint8Array(0));
  922. };