utils.js 29 KB

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