utils.js 32 KB

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