utils.js 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  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. /** @const @private {number} '0' */
  379. jspb.utils.ZERO_CHAR_CODE_ = 48;
  380. /** @const @private {number} 'a' */
  381. jspb.utils.A_CHAR_CODE_ = 97;
  382. /**
  383. * Losslessly converts a 64-bit unsigned integer in 32:32 split representation
  384. * into a decimal string.
  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 {string} The binary number represented as a string.
  388. */
  389. jspb.utils.joinUnsignedDecimalString = function(bitsLow, bitsHigh) {
  390. // Skip the expensive conversion if the number is small enough to use the
  391. // built-in conversions.
  392. if (bitsHigh <= 0x1FFFFF) {
  393. return '' + (jspb.BinaryConstants.TWO_TO_32 * bitsHigh + bitsLow);
  394. }
  395. // What this code is doing is essentially converting the input number from
  396. // base-2 to base-1e7, which allows us to represent the 64-bit range with
  397. // only 3 (very large) digits. Those digits are then trivial to convert to
  398. // a base-10 string.
  399. // The magic numbers used here are -
  400. // 2^24 = 16777216 = (1,6777216) in base-1e7.
  401. // 2^48 = 281474976710656 = (2,8147497,6710656) in base-1e7.
  402. // Split 32:32 representation into 16:24:24 representation so our
  403. // intermediate digits don't overflow.
  404. var low = bitsLow & 0xFFFFFF;
  405. var mid = (((bitsLow >>> 24) | (bitsHigh << 8)) >>> 0) & 0xFFFFFF;
  406. var high = (bitsHigh >> 16) & 0xFFFF;
  407. // Assemble our three base-1e7 digits, ignoring carries. The maximum
  408. // value in a digit at this step is representable as a 48-bit integer, which
  409. // can be stored in a 64-bit floating point number.
  410. var digitA = low + (mid * 6777216) + (high * 6710656);
  411. var digitB = mid + (high * 8147497);
  412. var digitC = (high * 2);
  413. // Apply carries from A to B and from B to C.
  414. var base = 10000000;
  415. if (digitA >= base) {
  416. digitB += Math.floor(digitA / base);
  417. digitA %= base;
  418. }
  419. if (digitB >= base) {
  420. digitC += Math.floor(digitB / base);
  421. digitB %= base;
  422. }
  423. // Convert base-1e7 digits to base-10, with optional leading zeroes.
  424. function decimalFrom1e7(digit1e7, needLeadingZeros) {
  425. var partial = digit1e7 ? String(digit1e7) : '';
  426. if (needLeadingZeros) {
  427. return '0000000'.slice(partial.length) + partial;
  428. }
  429. return partial;
  430. }
  431. return decimalFrom1e7(digitC, /*needLeadingZeros=*/ 0) +
  432. decimalFrom1e7(digitB, /*needLeadingZeros=*/ digitC) +
  433. // If the final 1e7 digit didn't need leading zeros, we would have
  434. // returned via the trivial code path at the top.
  435. decimalFrom1e7(digitA, /*needLeadingZeros=*/ 1);
  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 a signed or unsigned decimal string into its hash string
  489. * representation.
  490. * @param {string} dec
  491. * @return {string}
  492. */
  493. jspb.utils.decimalStringToHash64 = function(dec) {
  494. goog.asserts.assert(dec.length > 0);
  495. // Check for minus sign.
  496. var minus = false;
  497. if (dec[0] === '-') {
  498. minus = true;
  499. dec = dec.slice(1);
  500. }
  501. // Store result as a byte array.
  502. var resultBytes = [0, 0, 0, 0, 0, 0, 0, 0];
  503. // Set result to m*result + c.
  504. function muladd(m, c) {
  505. for (var i = 0; i < 8 && (m !== 1 || c > 0); i++) {
  506. var r = m * resultBytes[i] + c;
  507. resultBytes[i] = r & 0xFF;
  508. c = r >>> 8;
  509. }
  510. }
  511. // Negate the result bits.
  512. function neg() {
  513. for (var i = 0; i < 8; i++) {
  514. resultBytes[i] = (~resultBytes[i]) & 0xFF;
  515. }
  516. }
  517. // For each decimal digit, set result to 10*result + digit.
  518. for (var i = 0; i < dec.length; i++) {
  519. muladd(10, dec.charCodeAt(i) - jspb.utils.ZERO_CHAR_CODE_);
  520. }
  521. // If there's a minus sign, convert into two's complement.
  522. if (minus) {
  523. neg();
  524. muladd(1, 1);
  525. }
  526. return goog.crypt.byteArrayToString(resultBytes);
  527. };
  528. /**
  529. * Converts a signed or unsigned decimal string into two 32-bit halves, and
  530. * stores them in the temp variables listed above.
  531. * @param {string} value The decimal string to convert.
  532. */
  533. jspb.utils.splitDecimalString = function(value) {
  534. jspb.utils.splitHash64(jspb.utils.decimalStringToHash64(value));
  535. };
  536. /**
  537. * @param {number} nibble A 4-bit integer.
  538. * @return {string}
  539. * @private
  540. */
  541. jspb.utils.toHexDigit_ = function(nibble) {
  542. return String.fromCharCode(
  543. nibble < 10 ? jspb.utils.ZERO_CHAR_CODE_ + nibble :
  544. jspb.utils.A_CHAR_CODE_ - 10 + nibble);
  545. };
  546. /**
  547. * @param {number} hexCharCode
  548. * @return {number}
  549. * @private
  550. */
  551. jspb.utils.fromHexCharCode_ = function(hexCharCode) {
  552. if (hexCharCode >= jspb.utils.A_CHAR_CODE_) {
  553. return hexCharCode - jspb.utils.A_CHAR_CODE_ + 10;
  554. }
  555. return hexCharCode - jspb.utils.ZERO_CHAR_CODE_;
  556. };
  557. /**
  558. * Converts an 8-character hash string into its hexadecimal representation.
  559. * @param {string} hash
  560. * @return {string}
  561. */
  562. jspb.utils.hash64ToHexString = function(hash) {
  563. var temp = new Array(18);
  564. temp[0] = '0';
  565. temp[1] = 'x';
  566. for (var i = 0; i < 8; i++) {
  567. var c = hash.charCodeAt(7 - i);
  568. temp[i * 2 + 2] = jspb.utils.toHexDigit_(c >> 4);
  569. temp[i * 2 + 3] = jspb.utils.toHexDigit_(c & 0xF);
  570. }
  571. var result = temp.join('');
  572. return result;
  573. };
  574. /**
  575. * Converts a '0x<16 digits>' hex string into its hash string representation.
  576. * @param {string} hex
  577. * @return {string}
  578. */
  579. jspb.utils.hexStringToHash64 = function(hex) {
  580. hex = hex.toLowerCase();
  581. goog.asserts.assert(hex.length == 18);
  582. goog.asserts.assert(hex[0] == '0');
  583. goog.asserts.assert(hex[1] == 'x');
  584. var result = '';
  585. for (var i = 0; i < 8; i++) {
  586. var hi = jspb.utils.fromHexCharCode_(hex.charCodeAt(i * 2 + 2));
  587. var lo = jspb.utils.fromHexCharCode_(hex.charCodeAt(i * 2 + 3));
  588. result = String.fromCharCode(hi * 16 + lo) + result;
  589. }
  590. return result;
  591. };
  592. /**
  593. * Convert an 8-character hash string representing either a signed or unsigned
  594. * 64-bit integer into a Javascript number. Will lose accuracy if the result is
  595. * larger than 2^52.
  596. * @param {string} hash The hash string to convert.
  597. * @param {boolean} signed True if the has should be interpreted as a signed
  598. * number.
  599. * @return {number}
  600. */
  601. jspb.utils.hash64ToNumber = function(hash, signed) {
  602. jspb.utils.splitHash64(hash);
  603. var bitsLow = jspb.utils.split64Low;
  604. var bitsHigh = jspb.utils.split64High;
  605. return signed ? jspb.utils.joinInt64(bitsLow, bitsHigh) :
  606. jspb.utils.joinUint64(bitsLow, bitsHigh);
  607. };
  608. /**
  609. * Convert a Javascript number into an 8-character hash string. Will lose
  610. * precision if the value is non-integral or greater than 2^64.
  611. * @param {number} value The integer to convert.
  612. * @return {string}
  613. */
  614. jspb.utils.numberToHash64 = function(value) {
  615. jspb.utils.splitInt64(value);
  616. return jspb.utils.joinHash64(jspb.utils.split64Low,
  617. jspb.utils.split64High);
  618. };
  619. /**
  620. * Counts the number of contiguous varints in a buffer.
  621. * @param {!Uint8Array} buffer The buffer to scan.
  622. * @param {number} start The starting point in the buffer to scan.
  623. * @param {number} end The end point in the buffer to scan.
  624. * @return {number} The number of varints in the buffer.
  625. */
  626. jspb.utils.countVarints = function(buffer, start, end) {
  627. // Count how many high bits of each byte were set in the buffer.
  628. var count = 0;
  629. for (var i = start; i < end; i++) {
  630. count += buffer[i] >> 7;
  631. }
  632. // The number of varints in the buffer equals the size of the buffer minus
  633. // the number of non-terminal bytes in the buffer (those with the high bit
  634. // set).
  635. return (end - start) - count;
  636. };
  637. /**
  638. * Counts the number of contiguous varint fields with the given field number in
  639. * the buffer.
  640. * @param {!Uint8Array} buffer The buffer to scan.
  641. * @param {number} start The starting point in the buffer to scan.
  642. * @param {number} end The end point in the buffer to scan.
  643. * @param {number} field The field number to count.
  644. * @return {number} The number of matching fields in the buffer.
  645. */
  646. jspb.utils.countVarintFields = function(buffer, start, end, field) {
  647. var count = 0;
  648. var cursor = start;
  649. var tag = field * 8 + jspb.BinaryConstants.WireType.VARINT;
  650. if (tag < 128) {
  651. // Single-byte field tag, we can use a slightly quicker count.
  652. while (cursor < end) {
  653. // Skip the field tag, or exit if we find a non-matching tag.
  654. if (buffer[cursor++] != tag) return count;
  655. // Field tag matches, we've found a valid field.
  656. count++;
  657. // Skip the varint.
  658. while (1) {
  659. var x = buffer[cursor++];
  660. if ((x & 0x80) == 0) break;
  661. }
  662. }
  663. } else {
  664. while (cursor < end) {
  665. // Skip the field tag, or exit if we find a non-matching tag.
  666. var temp = tag;
  667. while (temp > 128) {
  668. if (buffer[cursor] != ((temp & 0x7F) | 0x80)) return count;
  669. cursor++;
  670. temp >>= 7;
  671. }
  672. if (buffer[cursor++] != temp) return count;
  673. // Field tag matches, we've found a valid field.
  674. count++;
  675. // Skip the varint.
  676. while (1) {
  677. var x = buffer[cursor++];
  678. if ((x & 0x80) == 0) break;
  679. }
  680. }
  681. }
  682. return count;
  683. };
  684. /**
  685. * Counts the number of contiguous fixed32 fields with the given tag in the
  686. * buffer.
  687. * @param {!Uint8Array} buffer The buffer to scan.
  688. * @param {number} start The starting point in the buffer to scan.
  689. * @param {number} end The end point in the buffer to scan.
  690. * @param {number} tag The tag value to count.
  691. * @param {number} stride The number of bytes to skip per field.
  692. * @return {number} The number of fields with a matching tag in the buffer.
  693. * @private
  694. */
  695. jspb.utils.countFixedFields_ =
  696. function(buffer, start, end, tag, stride) {
  697. var count = 0;
  698. var cursor = start;
  699. if (tag < 128) {
  700. // Single-byte field tag, we can use a slightly quicker count.
  701. while (cursor < end) {
  702. // Skip the field tag, or exit if we find a non-matching tag.
  703. if (buffer[cursor++] != tag) return count;
  704. // Field tag matches, we've found a valid field.
  705. count++;
  706. // Skip the value.
  707. cursor += stride;
  708. }
  709. } else {
  710. while (cursor < end) {
  711. // Skip the field tag, or exit if we find a non-matching tag.
  712. var temp = tag;
  713. while (temp > 128) {
  714. if (buffer[cursor++] != ((temp & 0x7F) | 0x80)) return count;
  715. temp >>= 7;
  716. }
  717. if (buffer[cursor++] != temp) return count;
  718. // Field tag matches, we've found a valid field.
  719. count++;
  720. // Skip the value.
  721. cursor += stride;
  722. }
  723. }
  724. return count;
  725. };
  726. /**
  727. * Counts the number of contiguous fixed32 fields with the given field number
  728. * in the buffer.
  729. * @param {!Uint8Array} buffer The buffer to scan.
  730. * @param {number} start The starting point in the buffer to scan.
  731. * @param {number} end The end point in the buffer to scan.
  732. * @param {number} field The field number to count.
  733. * @return {number} The number of matching fields in the buffer.
  734. */
  735. jspb.utils.countFixed32Fields = function(buffer, start, end, field) {
  736. var tag = field * 8 + jspb.BinaryConstants.WireType.FIXED32;
  737. return jspb.utils.countFixedFields_(buffer, start, end, tag, 4);
  738. };
  739. /**
  740. * Counts the number of contiguous fixed64 fields with the given field number
  741. * in the 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} field The field number to count
  746. * @return {number} The number of matching fields in the buffer.
  747. */
  748. jspb.utils.countFixed64Fields = function(buffer, start, end, field) {
  749. var tag = field * 8 + jspb.BinaryConstants.WireType.FIXED64;
  750. return jspb.utils.countFixedFields_(buffer, start, end, tag, 8);
  751. };
  752. /**
  753. * Counts the number of contiguous delimited fields with the given field number
  754. * in the buffer.
  755. * @param {!Uint8Array} buffer The buffer to scan.
  756. * @param {number} start The starting point in the buffer to scan.
  757. * @param {number} end The end point in the buffer to scan.
  758. * @param {number} field The field number to count.
  759. * @return {number} The number of matching fields in the buffer.
  760. */
  761. jspb.utils.countDelimitedFields = function(buffer, start, end, field) {
  762. var count = 0;
  763. var cursor = start;
  764. var tag = field * 8 + jspb.BinaryConstants.WireType.DELIMITED;
  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. // Decode the length prefix.
  776. var length = 0;
  777. var shift = 1;
  778. while (1) {
  779. temp = buffer[cursor++];
  780. length += (temp & 0x7f) * shift;
  781. shift *= 128;
  782. if ((temp & 0x80) == 0) break;
  783. }
  784. // Advance the cursor past the blob.
  785. cursor += length;
  786. }
  787. return count;
  788. };
  789. /**
  790. * String-ify bytes for text format. Should be optimized away in non-debug.
  791. * The returned string uses \xXX escapes for all values and is itself quoted.
  792. * [1, 31] serializes to '"\x01\x1f"'.
  793. * @param {jspb.ByteSource} byteSource The bytes to serialize.
  794. * @return {string} Stringified bytes for text format.
  795. */
  796. jspb.utils.debugBytesToTextFormat = function(byteSource) {
  797. var s = '"';
  798. if (byteSource) {
  799. var bytes = jspb.utils.byteSourceToUint8Array(byteSource);
  800. for (var i = 0; i < bytes.length; i++) {
  801. s += '\\x';
  802. if (bytes[i] < 16) s += '0';
  803. s += bytes[i].toString(16);
  804. }
  805. }
  806. return s + '"';
  807. };
  808. /**
  809. * String-ify a scalar for text format. Should be optimized away in non-debug.
  810. * @param {string|number|boolean} scalar The scalar to stringify.
  811. * @return {string} Stringified scalar for text format.
  812. */
  813. jspb.utils.debugScalarToTextFormat = function(scalar) {
  814. if (goog.isString(scalar)) {
  815. return goog.string.quote(scalar);
  816. } else {
  817. return scalar.toString();
  818. }
  819. };
  820. /**
  821. * Utility function: convert a string with codepoints 0--255 inclusive to a
  822. * Uint8Array. If any codepoints greater than 255 exist in the string, throws an
  823. * exception.
  824. * @param {string} str
  825. * @return {!Uint8Array}
  826. */
  827. jspb.utils.stringToByteArray = function(str) {
  828. var arr = new Uint8Array(str.length);
  829. for (var i = 0; i < str.length; i++) {
  830. var codepoint = str.charCodeAt(i);
  831. if (codepoint > 255) {
  832. throw new Error('Conversion error: string contains codepoint ' +
  833. 'outside of byte range');
  834. }
  835. arr[i] = codepoint;
  836. }
  837. return arr;
  838. };
  839. /**
  840. * Converts any type defined in jspb.ByteSource into a Uint8Array.
  841. * @param {!jspb.ByteSource} data
  842. * @return {!Uint8Array}
  843. * @suppress {invalidCasts}
  844. */
  845. jspb.utils.byteSourceToUint8Array = function(data) {
  846. if (data.constructor === Uint8Array) {
  847. return /** @type {!Uint8Array} */(data);
  848. }
  849. if (data.constructor === ArrayBuffer) {
  850. data = /** @type {!ArrayBuffer} */(data);
  851. return /** @type {!Uint8Array} */(new Uint8Array(data));
  852. }
  853. if (typeof Buffer != 'undefined' && data.constructor === Buffer) {
  854. return /** @type {!Uint8Array} */ (
  855. new Uint8Array(/** @type {?} */ (data)));
  856. }
  857. if (data.constructor === Array) {
  858. data = /** @type {!Array<number>} */(data);
  859. return /** @type {!Uint8Array} */(new Uint8Array(data));
  860. }
  861. if (data.constructor === String) {
  862. data = /** @type {string} */(data);
  863. return goog.crypt.base64.decodeStringToUint8Array(data);
  864. }
  865. goog.asserts.fail('Type not convertible to Uint8Array.');
  866. return /** @type {!Uint8Array} */(new Uint8Array(0));
  867. };