utils.js 31 KB

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