utils_test.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  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 Test cases for jspb's helper functions.
  32. *
  33. * Test suite is written using Jasmine -- see http://jasmine.github.io/
  34. *
  35. * @author aappleby@google.com (Austin Appleby)
  36. */
  37. goog.require('goog.crypt');
  38. goog.require('goog.crypt.base64');
  39. goog.require('jspb.BinaryConstants');
  40. goog.require('jspb.BinaryWriter');
  41. goog.require('jspb.utils');
  42. /**
  43. * @param {number} x
  44. * @return {number}
  45. */
  46. function truncate(x) {
  47. var temp = new Float32Array(1);
  48. temp[0] = x;
  49. return temp[0];
  50. }
  51. /**
  52. * Converts an 64-bit integer in split representation to a 64-bit hash string
  53. * (8 bits encoded per character).
  54. * @param {number} bitsLow The low 32 bits of the split 64-bit integer.
  55. * @param {number} bitsHigh The high 32 bits of the split 64-bit integer.
  56. * @return {string} The encoded hash string, 8 bits per character.
  57. */
  58. function toHashString(bitsLow, bitsHigh) {
  59. return String.fromCharCode((bitsLow >>> 0) & 0xFF,
  60. (bitsLow >>> 8) & 0xFF,
  61. (bitsLow >>> 16) & 0xFF,
  62. (bitsLow >>> 24) & 0xFF,
  63. (bitsHigh >>> 0) & 0xFF,
  64. (bitsHigh >>> 8) & 0xFF,
  65. (bitsHigh >>> 16) & 0xFF,
  66. (bitsHigh >>> 24) & 0xFF);
  67. }
  68. describe('binaryUtilsTest', function() {
  69. /**
  70. * Tests lossless binary-to-decimal conversion.
  71. */
  72. it('testDecimalConversion', function() {
  73. // Check some magic numbers.
  74. var result =
  75. jspb.utils.joinUnsignedDecimalString(0x89e80001, 0x8ac72304);
  76. expect(result).toEqual('10000000000000000001');
  77. result = jspb.utils.joinUnsignedDecimalString(0xacd05f15, 0x1b69b4b);
  78. expect(result).toEqual('123456789123456789');
  79. result = jspb.utils.joinUnsignedDecimalString(0xeb1f0ad2, 0xab54a98c);
  80. expect(result).toEqual('12345678901234567890');
  81. result = jspb.utils.joinUnsignedDecimalString(0xe3b70cb1, 0x891087b8);
  82. expect(result).toEqual('9876543210987654321');
  83. // Check limits.
  84. result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x00000000);
  85. expect(result).toEqual('0');
  86. result = jspb.utils.joinUnsignedDecimalString(0xFFFFFFFF, 0xFFFFFFFF);
  87. expect(result).toEqual('18446744073709551615');
  88. // Check each bit of the low dword.
  89. for (var i = 0; i < 32; i++) {
  90. var low = (1 << i) >>> 0;
  91. result = jspb.utils.joinUnsignedDecimalString(low, 0);
  92. expect(result).toEqual('' + Math.pow(2, i));
  93. }
  94. // Check the first 20 bits of the high dword.
  95. for (var i = 0; i < 20; i++) {
  96. var high = (1 << i) >>> 0;
  97. result = jspb.utils.joinUnsignedDecimalString(0, high);
  98. expect(result).toEqual('' + Math.pow(2, 32 + i));
  99. }
  100. // V8's internal double-to-string conversion is inaccurate for values above
  101. // 2^52, even if they're representable integers - check the rest of the bits
  102. // manually against the correct string representations of 2^N.
  103. result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x00100000);
  104. expect(result).toEqual('4503599627370496');
  105. result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x00200000);
  106. expect(result).toEqual('9007199254740992');
  107. result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x00400000);
  108. expect(result).toEqual('18014398509481984');
  109. result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x00800000);
  110. expect(result).toEqual('36028797018963968');
  111. result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x01000000);
  112. expect(result).toEqual('72057594037927936');
  113. result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x02000000);
  114. expect(result).toEqual('144115188075855872');
  115. result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x04000000);
  116. expect(result).toEqual('288230376151711744');
  117. result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x08000000);
  118. expect(result).toEqual('576460752303423488');
  119. result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x10000000);
  120. expect(result).toEqual('1152921504606846976');
  121. result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x20000000);
  122. expect(result).toEqual('2305843009213693952');
  123. result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x40000000);
  124. expect(result).toEqual('4611686018427387904');
  125. result = jspb.utils.joinUnsignedDecimalString(0x00000000, 0x80000000);
  126. expect(result).toEqual('9223372036854775808');
  127. });
  128. /**
  129. * Going from hash strings to decimal strings should also be lossless.
  130. */
  131. it('testHashToDecimalConversion', function() {
  132. var result;
  133. var convert = jspb.utils.hash64ToDecimalString;
  134. result = convert(toHashString(0x00000000, 0x00000000), false);
  135. expect(result).toEqual('0');
  136. result = convert(toHashString(0x00000000, 0x00000000), true);
  137. expect(result).toEqual('0');
  138. result = convert(toHashString(0xFFFFFFFF, 0xFFFFFFFF), false);
  139. expect(result).toEqual('18446744073709551615');
  140. result = convert(toHashString(0xFFFFFFFF, 0xFFFFFFFF), true);
  141. expect(result).toEqual('-1');
  142. result = convert(toHashString(0x00000000, 0x80000000), false);
  143. expect(result).toEqual('9223372036854775808');
  144. result = convert(toHashString(0x00000000, 0x80000000), true);
  145. expect(result).toEqual('-9223372036854775808');
  146. result = convert(toHashString(0xacd05f15, 0x01b69b4b), false);
  147. expect(result).toEqual('123456789123456789');
  148. result = convert(toHashString(~0xacd05f15 + 1, ~0x01b69b4b), true);
  149. expect(result).toEqual('-123456789123456789');
  150. // And converting arrays of hashes should work the same way.
  151. result = jspb.utils.hash64ArrayToDecimalStrings([
  152. toHashString(0xFFFFFFFF, 0xFFFFFFFF),
  153. toHashString(0x00000000, 0x80000000),
  154. toHashString(0xacd05f15, 0x01b69b4b)], false);
  155. expect(result.length).toEqual(3);
  156. expect(result[0]).toEqual('18446744073709551615');
  157. expect(result[1]).toEqual('9223372036854775808');
  158. expect(result[2]).toEqual('123456789123456789');
  159. });
  160. /*
  161. * Going from decimal strings to hash strings should be lossless.
  162. */
  163. it('testDecimalToHashConversion', function() {
  164. var result;
  165. var convert = jspb.utils.decimalStringToHash64;
  166. result = convert('0');
  167. expect(result).toEqual(goog.crypt.byteArrayToString(
  168. [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]));
  169. result = convert('-1');
  170. expect(result).toEqual(goog.crypt.byteArrayToString(
  171. [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]));
  172. result = convert('18446744073709551615');
  173. expect(result).toEqual(goog.crypt.byteArrayToString(
  174. [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]));
  175. result = convert('9223372036854775808');
  176. expect(result).toEqual(goog.crypt.byteArrayToString(
  177. [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80]));
  178. result = convert('-9223372036854775808');
  179. expect(result).toEqual(goog.crypt.byteArrayToString(
  180. [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80]));
  181. result = convert('123456789123456789');
  182. expect(result).toEqual(goog.crypt.byteArrayToString(
  183. [0x15, 0x5F, 0xD0, 0xAC, 0x4B, 0x9B, 0xB6, 0x01]));
  184. result = convert('-123456789123456789');
  185. expect(result).toEqual(goog.crypt.byteArrayToString(
  186. [0xEB, 0xA0, 0x2F, 0x53, 0xB4, 0x64, 0x49, 0xFE]));
  187. });
  188. /**
  189. * Going from hash strings to hex strings should be lossless.
  190. */
  191. it('testHashToHexConversion', function() {
  192. var result;
  193. var convert = jspb.utils.hash64ToHexString;
  194. result = convert(toHashString(0x00000000, 0x00000000));
  195. expect(result).toEqual('0x0000000000000000');
  196. result = convert(toHashString(0xFFFFFFFF, 0xFFFFFFFF));
  197. expect(result).toEqual('0xffffffffffffffff');
  198. result = convert(toHashString(0x12345678, 0x9ABCDEF0));
  199. expect(result).toEqual('0x9abcdef012345678');
  200. });
  201. /**
  202. * Going from hex strings to hash strings should be lossless.
  203. */
  204. it('testHexToHashConversion', function() {
  205. var result;
  206. var convert = jspb.utils.hexStringToHash64;
  207. result = convert('0x0000000000000000');
  208. expect(result).toEqual(goog.crypt.byteArrayToString(
  209. [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]));
  210. result = convert('0xffffffffffffffff');
  211. expect(result).toEqual(goog.crypt.byteArrayToString(
  212. [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]));
  213. // Hex string is big-endian, hash string is little-endian.
  214. result = convert('0x123456789ABCDEF0');
  215. expect(result).toEqual(goog.crypt.byteArrayToString(
  216. [0xF0, 0xDE, 0xBC, 0x9A, 0x78, 0x56, 0x34, 0x12]));
  217. // Capitalization should not matter.
  218. result = convert('0x0000abcdefABCDEF');
  219. expect(result).toEqual(goog.crypt.byteArrayToString(
  220. [0xEF, 0xCD, 0xAB, 0xEF, 0xCD, 0xAB, 0x00, 0x00]));
  221. });
  222. /**
  223. * Going from numbers to hash strings should be lossless for up to 53 bits of
  224. * precision.
  225. */
  226. it('testNumberToHashConversion', function() {
  227. var result;
  228. var convert = jspb.utils.numberToHash64;
  229. result = convert(0x0000000000000);
  230. expect(jspb.utils.hash64ToHexString(result)).toEqual('0x0000000000000000');
  231. result = convert(0xFFFFFFFFFFFFF);
  232. expect(jspb.utils.hash64ToHexString(result)).toEqual('0x000fffffffffffff');
  233. result = convert(0x123456789ABCD);
  234. expect(jspb.utils.hash64ToHexString(result)).toEqual('0x000123456789abcd');
  235. result = convert(0xDCBA987654321);
  236. expect(jspb.utils.hash64ToHexString(result)).toEqual('0x000dcba987654321');
  237. // 53 bits of precision should not be truncated.
  238. result = convert(0x10000000000001);
  239. expect(jspb.utils.hash64ToHexString(result)).toEqual('0x0010000000000001');
  240. // 54 bits of precision should be truncated.
  241. result = convert(0x20000000000001);
  242. expect(jspb.utils.hash64ToHexString(result))
  243. .not.toEqual('0x0020000000000001');
  244. });
  245. /**
  246. * Sanity check the behavior of Javascript's strings when doing funny things
  247. * with unicode characters.
  248. */
  249. it('sanityCheckUnicodeStrings', function() {
  250. var strings = new Array(65536);
  251. // All possible unsigned 16-bit values should be storable in a string, they
  252. // shouldn't do weird things with the length of the string, and they should
  253. // come back out of the string unchanged.
  254. for (var i = 0; i < 65536; i++) {
  255. strings[i] = 'a' + String.fromCharCode(i) + 'a';
  256. expect(strings[i].length).toEqual(3);
  257. expect(strings[i].charCodeAt(1)).toEqual(i);
  258. }
  259. // Each unicode character should compare equal to itself and not equal to a
  260. // different unicode character.
  261. for (var i = 0; i < 65536; i++) {
  262. expect(strings[i] == strings[i]).toEqual(true);
  263. expect(strings[i] == strings[(i + 1) % 65536]).toEqual(false);
  264. }
  265. });
  266. /**
  267. * Tests conversion from 32-bit floating point numbers to split64 numbers.
  268. */
  269. it('testFloat32ToSplit64', function() {
  270. var f32_eps = jspb.BinaryConstants.FLOAT32_EPS;
  271. var f32_min = jspb.BinaryConstants.FLOAT32_MIN;
  272. var f32_max = jspb.BinaryConstants.FLOAT32_MAX;
  273. var f32_max_safe_int = jspb.utils.joinFloat32(0x4b7fffff, 0);
  274. var f32_pi = Math.fround(Math.PI);
  275. // NaN.
  276. jspb.utils.splitFloat32(NaN);
  277. expect(isNaN(jspb.utils.joinFloat32(
  278. jspb.utils.split64Low, jspb.utils.split64High)))
  279. .toEqual(true);
  280. /**
  281. * @param {number} x
  282. * @param {number=} opt_bits
  283. */
  284. function test(x, opt_bits) {
  285. jspb.utils.splitFloat32(x);
  286. if (opt_bits !== undefined) {
  287. if (opt_bits != jspb.utils.split64Low) throw 'fail!';
  288. }
  289. expect(truncate(x))
  290. .toEqual(jspb.utils.joinFloat32(
  291. jspb.utils.split64Low, jspb.utils.split64High));
  292. }
  293. // Positive and negative infinity.
  294. test(Infinity, 0x7f800000);
  295. test(-Infinity, 0xff800000);
  296. // Positive and negative zero.
  297. test(0, 0x00000000);
  298. test(-0, 0x80000000);
  299. // Positive and negative epsilon.
  300. test(f32_eps, 0x00000001);
  301. test(-f32_eps, 0x80000001);
  302. // Positive and negative min.
  303. test(f32_min, 0x00800000);
  304. test(-f32_min, 0x80800000);
  305. // Positive and negative max.
  306. test(f32_max, 0x7F7FFFFF);
  307. test(-f32_max, 0xFF7FFFFF);
  308. // Positive and negative max_safe_int.
  309. test(f32_max_safe_int, 0x4B7FFFFF);
  310. test(-f32_max_safe_int, 0xCB7FFFFF);
  311. // Pi.
  312. test(f32_pi, 0x40490fdb);
  313. // corner cases
  314. test(0.9999999762949594, 0x3f800000);
  315. test(7.99999999999999, 0x41000000);
  316. test(Math.sin(30 * Math.PI / 180), 0x3f000000); // sin(30 degrees)
  317. // Various positive values.
  318. var cursor = f32_eps * 10;
  319. while (cursor != Infinity) {
  320. test(cursor);
  321. cursor *= 1.1;
  322. }
  323. // Various negative values.
  324. cursor = -f32_eps * 10;
  325. while (cursor != -Infinity) {
  326. test(cursor);
  327. cursor *= 1.1;
  328. }
  329. });
  330. /**
  331. * Tests conversion from 64-bit floating point numbers to split64 numbers.
  332. */
  333. it('testFloat64ToSplit64', function() {
  334. var f64_eps = jspb.BinaryConstants.FLOAT64_EPS;
  335. var f64_min = jspb.BinaryConstants.FLOAT64_MIN;
  336. var f64_max = jspb.BinaryConstants.FLOAT64_MAX;
  337. // NaN.
  338. jspb.utils.splitFloat64(NaN);
  339. expect(isNaN(jspb.utils.joinFloat64(
  340. jspb.utils.split64Low, jspb.utils.split64High)))
  341. .toEqual(true);
  342. /**
  343. * @param {number} x
  344. * @param {number=} opt_highBits
  345. * @param {number=} opt_lowBits
  346. */
  347. function test(x, opt_highBits, opt_lowBits) {
  348. jspb.utils.splitFloat64(x);
  349. if (opt_highBits !== undefined) {
  350. var split64High = jspb.utils.split64High;
  351. expect(opt_highBits.toString(16)).toEqual(split64High.toString(16));
  352. }
  353. if (opt_lowBits !== undefined) {
  354. var split64Low = jspb.utils.split64Low;
  355. expect(opt_lowBits.toString(16)).toEqual(split64Low.toString(16));
  356. }
  357. expect(
  358. jspb.utils.joinFloat64(jspb.utils.split64Low, jspb.utils.split64High))
  359. .toEqual(x);
  360. }
  361. // Positive and negative infinity.
  362. test(Infinity, 0x7ff00000, 0x00000000);
  363. test(-Infinity, 0xfff00000, 0x00000000);
  364. // Positive and negative zero.
  365. test(0, 0x00000000, 0x00000000);
  366. test(-0, 0x80000000, 0x00000000);
  367. test(1, 0x3FF00000, 0x00000000);
  368. test(2, 0x40000000, 0x00000000);
  369. // Positive and negative epsilon.
  370. test(f64_eps, 0x00000000, 0x00000001);
  371. test(-f64_eps, 0x80000000, 0x00000001);
  372. // Positive and negative min.
  373. test(f64_min, 0x00100000, 0x00000000);
  374. test(-f64_min, 0x80100000, 0x00000000);
  375. // Positive and negative max.
  376. test(f64_max, 0x7FEFFFFF, 0xFFFFFFFF);
  377. test(-f64_max, 0xFFEFFFFF, 0xFFFFFFFF);
  378. test(Number.MAX_SAFE_INTEGER, 0x433FFFFF, 0xFFFFFFFF);
  379. test(Number.MIN_SAFE_INTEGER, 0xC33FFFFF, 0xFFFFFFFF);
  380. // Test various edge cases with mantissa of all 1, all 0, or just the
  381. // highest or lowest significant bit.
  382. test(4503599627370497, 0x43300000, 0x00000001);
  383. test(6755399441055744, 0x43380000, 0x00000000);
  384. test(1.348269851146737e+308, 0x7FE80000, 0x00000000);
  385. test(1.9999999999999998, 0x3FFFFFFF, 0xFFFFFFFF);
  386. test(2.225073858507201e-308, 0x000FFFFF, 0xFFFFFFFF);
  387. test(Math.PI, 0x400921fb, 0x54442d18);
  388. test(jspb.BinaryConstants.FLOAT32_MIN, 0x38100000, 0x00000000);
  389. // Various positive values.
  390. var cursor = f64_eps * 10;
  391. while (cursor != Infinity) {
  392. test(cursor);
  393. cursor *= 1.1;
  394. }
  395. // Various negative values.
  396. cursor = -f64_eps * 10;
  397. while (cursor != -Infinity) {
  398. test(cursor);
  399. cursor *= 1.1;
  400. }
  401. });
  402. /**
  403. * Tests zigzag conversions.
  404. */
  405. it('can encode and decode zigzag 64', function() {
  406. function stringToHiLoPair(str) {
  407. jspb.utils.splitDecimalString(str);
  408. return {
  409. lo: jspb.utils.split64Low >>> 0,
  410. hi: jspb.utils.split64High >>> 0
  411. };
  412. }
  413. function makeHiLoPair(lo, hi) {
  414. return {lo: lo >>> 0, hi: hi >>> 0};
  415. }
  416. // Test cases directly from the protobuf dev guide.
  417. // https://engdoc.corp.google.com/eng/howto/protocolbuffers/developerguide/encoding.shtml?cl=head#types
  418. var testCases = [
  419. {original: stringToHiLoPair('0'), zigzag: stringToHiLoPair('0')},
  420. {original: stringToHiLoPair('-1'), zigzag: stringToHiLoPair('1')},
  421. {original: stringToHiLoPair('1'), zigzag: stringToHiLoPair('2')},
  422. {original: stringToHiLoPair('-2'), zigzag: stringToHiLoPair('3')},
  423. {
  424. original: stringToHiLoPair('2147483647'),
  425. zigzag: stringToHiLoPair('4294967294')
  426. },
  427. {
  428. original: stringToHiLoPair('-2147483648'),
  429. zigzag: stringToHiLoPair('4294967295')
  430. },
  431. // 64-bit extremes
  432. {
  433. original: stringToHiLoPair('9223372036854775807'),
  434. zigzag: stringToHiLoPair('18446744073709551614')
  435. },
  436. {
  437. original: stringToHiLoPair('-9223372036854775808'),
  438. zigzag: stringToHiLoPair('18446744073709551615')
  439. },
  440. ];
  441. for (const c of testCases) {
  442. expect(jspb.utils.toZigzag64(c.original.lo, c.original.hi, makeHiLoPair))
  443. .toEqual(c.zigzag);
  444. expect(jspb.utils.fromZigzag64(c.zigzag.lo, c.zigzag.hi, makeHiLoPair))
  445. .toEqual(c.original);
  446. }
  447. });
  448. /**
  449. * Tests counting packed varints.
  450. */
  451. it('testCountVarints', function() {
  452. var values = [];
  453. for (var i = 1; i < 1000000000; i *= 1.1) {
  454. values.push(Math.floor(i));
  455. }
  456. var writer = new jspb.BinaryWriter();
  457. writer.writePackedUint64(1, values);
  458. var buffer = new Uint8Array(writer.getResultBuffer());
  459. // We should have two more varints than we started with - one for the field
  460. // tag, one for the packed length.
  461. expect(jspb.utils.countVarints(buffer, 0, buffer.length))
  462. .toEqual(values.length + 2);
  463. });
  464. /**
  465. * Tests counting matching varint fields.
  466. */
  467. it('testCountVarintFields', function() {
  468. var writer = new jspb.BinaryWriter();
  469. var count = 0;
  470. for (var i = 1; i < 1000000000; i *= 1.1) {
  471. writer.writeUint64(1, Math.floor(i));
  472. count++;
  473. }
  474. writer.writeString(2, 'terminator');
  475. var buffer = new Uint8Array(writer.getResultBuffer());
  476. expect(jspb.utils.countVarintFields(buffer, 0, buffer.length, 1))
  477. .toEqual(count);
  478. writer = new jspb.BinaryWriter();
  479. count = 0;
  480. for (var i = 1; i < 1000000000; i *= 1.1) {
  481. writer.writeUint64(123456789, Math.floor(i));
  482. count++;
  483. }
  484. writer.writeString(2, 'terminator');
  485. buffer = new Uint8Array(writer.getResultBuffer());
  486. expect(jspb.utils.countVarintFields(buffer, 0, buffer.length, 123456789))
  487. .toEqual(count);
  488. });
  489. /**
  490. * Tests counting matching fixed32 fields.
  491. */
  492. it('testCountFixed32Fields', function() {
  493. var writer = new jspb.BinaryWriter();
  494. var count = 0;
  495. for (var i = 1; i < 1000000000; i *= 1.1) {
  496. writer.writeFixed32(1, Math.floor(i));
  497. count++;
  498. }
  499. writer.writeString(2, 'terminator');
  500. var buffer = new Uint8Array(writer.getResultBuffer());
  501. expect(jspb.utils.countFixed32Fields(buffer, 0, buffer.length, 1))
  502. .toEqual(count);
  503. writer = new jspb.BinaryWriter();
  504. count = 0;
  505. for (var i = 1; i < 1000000000; i *= 1.1) {
  506. writer.writeFixed32(123456789, Math.floor(i));
  507. count++;
  508. }
  509. writer.writeString(2, 'terminator');
  510. buffer = new Uint8Array(writer.getResultBuffer());
  511. expect(jspb.utils.countFixed32Fields(buffer, 0, buffer.length, 123456789))
  512. .toEqual(count);
  513. });
  514. /**
  515. * Tests counting matching fixed64 fields.
  516. */
  517. it('testCountFixed64Fields', function() {
  518. var writer = new jspb.BinaryWriter();
  519. var count = 0;
  520. for (var i = 1; i < 1000000000; i *= 1.1) {
  521. writer.writeDouble(1, i);
  522. count++;
  523. }
  524. writer.writeString(2, 'terminator');
  525. var buffer = new Uint8Array(writer.getResultBuffer());
  526. expect(jspb.utils.countFixed64Fields(buffer, 0, buffer.length, 1))
  527. .toEqual(count);
  528. writer = new jspb.BinaryWriter();
  529. count = 0;
  530. for (var i = 1; i < 1000000000; i *= 1.1) {
  531. writer.writeDouble(123456789, i);
  532. count++;
  533. }
  534. writer.writeString(2, 'terminator');
  535. buffer = new Uint8Array(writer.getResultBuffer());
  536. expect(jspb.utils.countFixed64Fields(buffer, 0, buffer.length, 123456789))
  537. .toEqual(count);
  538. });
  539. /**
  540. * Tests counting matching delimited fields.
  541. */
  542. it('testCountDelimitedFields', function() {
  543. var writer = new jspb.BinaryWriter();
  544. var count = 0;
  545. for (var i = 1; i < 1000; i *= 1.1) {
  546. writer.writeBytes(1, [Math.floor(i)]);
  547. count++;
  548. }
  549. writer.writeString(2, 'terminator');
  550. var buffer = new Uint8Array(writer.getResultBuffer());
  551. expect(jspb.utils.countDelimitedFields(buffer, 0, buffer.length, 1))
  552. .toEqual(count);
  553. writer = new jspb.BinaryWriter();
  554. count = 0;
  555. for (var i = 1; i < 1000; i *= 1.1) {
  556. writer.writeBytes(123456789, [Math.floor(i)]);
  557. count++;
  558. }
  559. writer.writeString(2, 'terminator');
  560. buffer = new Uint8Array(writer.getResultBuffer());
  561. expect(jspb.utils.countDelimitedFields(buffer, 0, buffer.length, 123456789))
  562. .toEqual(count);
  563. });
  564. /**
  565. * Tests byte format for debug strings.
  566. */
  567. it('testDebugBytesToTextFormat', function() {
  568. expect(jspb.utils.debugBytesToTextFormat(null)).toEqual('""');
  569. expect(jspb.utils.debugBytesToTextFormat([
  570. 0, 16, 255
  571. ])).toEqual('"\\x00\\x10\\xff"');
  572. });
  573. /**
  574. * Tests converting byte blob sources into byte blobs.
  575. */
  576. it('testByteSourceToUint8Array', function() {
  577. var convert = jspb.utils.byteSourceToUint8Array;
  578. var sourceData = [];
  579. for (var i = 0; i < 256; i++) {
  580. sourceData.push(i);
  581. }
  582. var sourceBytes = new Uint8Array(sourceData);
  583. var sourceBuffer = sourceBytes.buffer;
  584. var sourceBase64 = goog.crypt.base64.encodeByteArray(sourceData);
  585. var sourceString = goog.crypt.byteArrayToString(sourceData);
  586. function check(result) {
  587. expect(result.constructor).toEqual(Uint8Array);
  588. expect(result.length).toEqual(sourceData.length);
  589. for (var i = 0; i < result.length; i++) {
  590. expect(result[i]).toEqual(sourceData[i]);
  591. }
  592. }
  593. // Converting Uint8Arrays into Uint8Arrays should be a no-op.
  594. expect(convert(sourceBytes)).toEqual(sourceBytes);
  595. // Converting Array<numbers> into Uint8Arrays should work.
  596. check(convert(sourceData));
  597. // Converting ArrayBuffers into Uint8Arrays should work.
  598. check(convert(sourceBuffer));
  599. // Converting base64-encoded strings into Uint8Arrays should work.
  600. check(convert(sourceBase64));
  601. });
  602. });