decoder_test.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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 binary protocol buffer decoder.
  32. *
  33. * There are two particular magic numbers that need to be pointed out -
  34. * 2^64-1025 is the largest number representable as both a double and an
  35. * unsigned 64-bit integer, and 2^63-513 is the largest number representable as
  36. * both a double and a signed 64-bit integer.
  37. *
  38. * Test suite is written using Jasmine -- see http://jasmine.github.io/
  39. *
  40. * @author aappleby@google.com (Austin Appleby)
  41. */
  42. goog.require('goog.testing.asserts');
  43. goog.require('jspb.BinaryConstants');
  44. goog.require('jspb.BinaryDecoder');
  45. goog.require('jspb.BinaryEncoder');
  46. goog.require('jspb.utils');
  47. /**
  48. * Tests encoding and decoding of unsigned types.
  49. * @param {Function} readValue
  50. * @param {Function} writeValue
  51. * @param {number} epsilon
  52. * @param {number} upperLimit
  53. * @param {Function} filter
  54. * @suppress {missingProperties|visibility}
  55. */
  56. function doTestUnsignedValue(readValue,
  57. writeValue, epsilon, upperLimit, filter) {
  58. var encoder = new jspb.BinaryEncoder();
  59. // Encode zero and limits.
  60. writeValue.call(encoder, filter(0));
  61. writeValue.call(encoder, filter(epsilon));
  62. writeValue.call(encoder, filter(upperLimit));
  63. // Encode positive values.
  64. for (var cursor = epsilon; cursor < upperLimit; cursor *= 1.1) {
  65. writeValue.call(encoder, filter(cursor));
  66. }
  67. var decoder = jspb.BinaryDecoder.alloc(encoder.end());
  68. // Check zero and limits.
  69. assertEquals(filter(0), readValue.call(decoder));
  70. assertEquals(filter(epsilon), readValue.call(decoder));
  71. assertEquals(filter(upperLimit), readValue.call(decoder));
  72. // Check positive values.
  73. for (var cursor = epsilon; cursor < upperLimit; cursor *= 1.1) {
  74. if (filter(cursor) != readValue.call(decoder)) throw 'fail!';
  75. }
  76. // Encoding values outside the valid range should assert.
  77. assertThrows(function() {writeValue.call(encoder, -1);});
  78. assertThrows(function() {writeValue.call(encoder, upperLimit * 1.1);});
  79. }
  80. /**
  81. * Tests encoding and decoding of signed types.
  82. * @param {Function} readValue
  83. * @param {Function} writeValue
  84. * @param {number} epsilon
  85. * @param {number} lowerLimit
  86. * @param {number} upperLimit
  87. * @param {Function} filter
  88. * @suppress {missingProperties}
  89. */
  90. function doTestSignedValue(readValue,
  91. writeValue, epsilon, lowerLimit, upperLimit, filter) {
  92. var encoder = new jspb.BinaryEncoder();
  93. // Encode zero and limits.
  94. writeValue.call(encoder, filter(lowerLimit));
  95. writeValue.call(encoder, filter(-epsilon));
  96. writeValue.call(encoder, filter(0));
  97. writeValue.call(encoder, filter(epsilon));
  98. writeValue.call(encoder, filter(upperLimit));
  99. var inputValues = [];
  100. // Encode negative values.
  101. for (var cursor = lowerLimit; cursor < -epsilon; cursor /= 1.1) {
  102. var val = filter(cursor);
  103. writeValue.call(encoder, val);
  104. inputValues.push(val);
  105. }
  106. // Encode positive values.
  107. for (var cursor = epsilon; cursor < upperLimit; cursor *= 1.1) {
  108. var val = filter(cursor);
  109. writeValue.call(encoder, val);
  110. inputValues.push(val);
  111. }
  112. var decoder = jspb.BinaryDecoder.alloc(encoder.end());
  113. // Check zero and limits.
  114. assertEquals(filter(lowerLimit), readValue.call(decoder));
  115. assertEquals(filter(-epsilon), readValue.call(decoder));
  116. assertEquals(filter(0), readValue.call(decoder));
  117. assertEquals(filter(epsilon), readValue.call(decoder));
  118. assertEquals(filter(upperLimit), readValue.call(decoder));
  119. // Verify decoded values.
  120. for (var i = 0; i < inputValues.length; i++) {
  121. assertEquals(inputValues[i], readValue.call(decoder));
  122. }
  123. // Encoding values outside the valid range should assert.
  124. var pastLowerLimit = lowerLimit * 1.1;
  125. var pastUpperLimit = upperLimit * 1.1;
  126. if (pastLowerLimit !== -Infinity) {
  127. expect(() => void writeValue.call(encoder, pastLowerLimit)).toThrow();
  128. }
  129. if (pastUpperLimit !== Infinity) {
  130. expect(() => void writeValue.call(encoder, pastUpperLimit)).toThrow();
  131. }
  132. }
  133. describe('binaryDecoderTest', function() {
  134. /**
  135. * Tests the decoder instance cache.
  136. */
  137. it('testInstanceCache', /** @suppress {visibility} */ function() {
  138. // Empty the instance caches.
  139. jspb.BinaryDecoder.instanceCache_ = [];
  140. // Allocating and then freeing a decoder should put it in the instance
  141. // cache.
  142. jspb.BinaryDecoder.alloc().free();
  143. assertEquals(1, jspb.BinaryDecoder.instanceCache_.length);
  144. // Allocating and then freeing three decoders should leave us with three in
  145. // the cache.
  146. var decoder1 = jspb.BinaryDecoder.alloc();
  147. var decoder2 = jspb.BinaryDecoder.alloc();
  148. var decoder3 = jspb.BinaryDecoder.alloc();
  149. decoder1.free();
  150. decoder2.free();
  151. decoder3.free();
  152. assertEquals(3, jspb.BinaryDecoder.instanceCache_.length);
  153. });
  154. describe('varint64', function() {
  155. var /** !jspb.BinaryEncoder */ encoder;
  156. var /** !jspb.BinaryDecoder */ decoder;
  157. var hashA = String.fromCharCode(0x00, 0x00, 0x00, 0x00,
  158. 0x00, 0x00, 0x00, 0x00);
  159. var hashB = String.fromCharCode(0x12, 0x34, 0x00, 0x00,
  160. 0x00, 0x00, 0x00, 0x00);
  161. var hashC = String.fromCharCode(0x12, 0x34, 0x56, 0x78,
  162. 0x87, 0x65, 0x43, 0x21);
  163. var hashD = String.fromCharCode(0xFF, 0xFF, 0xFF, 0xFF,
  164. 0xFF, 0xFF, 0xFF, 0xFF);
  165. beforeEach(function() {
  166. encoder = new jspb.BinaryEncoder();
  167. encoder.writeVarintHash64(hashA);
  168. encoder.writeVarintHash64(hashB);
  169. encoder.writeVarintHash64(hashC);
  170. encoder.writeVarintHash64(hashD);
  171. encoder.writeFixedHash64(hashA);
  172. encoder.writeFixedHash64(hashB);
  173. encoder.writeFixedHash64(hashC);
  174. encoder.writeFixedHash64(hashD);
  175. decoder = jspb.BinaryDecoder.alloc(encoder.end());
  176. });
  177. it('reads 64-bit integers as hash strings', function() {
  178. assertEquals(hashA, decoder.readVarintHash64());
  179. assertEquals(hashB, decoder.readVarintHash64());
  180. assertEquals(hashC, decoder.readVarintHash64());
  181. assertEquals(hashD, decoder.readVarintHash64());
  182. assertEquals(hashA, decoder.readFixedHash64());
  183. assertEquals(hashB, decoder.readFixedHash64());
  184. assertEquals(hashC, decoder.readFixedHash64());
  185. assertEquals(hashD, decoder.readFixedHash64());
  186. });
  187. it('reads split 64 bit integers', function() {
  188. function hexJoin(bitsLow, bitsHigh) {
  189. return `0x${(bitsHigh >>> 0).toString(16)}:0x${
  190. (bitsLow >>> 0).toString(16)}`;
  191. }
  192. function hexJoinHash(hash64) {
  193. jspb.utils.splitHash64(hash64);
  194. return hexJoin(jspb.utils.split64Low, jspb.utils.split64High);
  195. }
  196. expect(decoder.readSplitVarint64(hexJoin)).toEqual(hexJoinHash(hashA));
  197. expect(decoder.readSplitVarint64(hexJoin)).toEqual(hexJoinHash(hashB));
  198. expect(decoder.readSplitVarint64(hexJoin)).toEqual(hexJoinHash(hashC));
  199. expect(decoder.readSplitVarint64(hexJoin)).toEqual(hexJoinHash(hashD));
  200. expect(decoder.readSplitFixed64(hexJoin)).toEqual(hexJoinHash(hashA));
  201. expect(decoder.readSplitFixed64(hexJoin)).toEqual(hexJoinHash(hashB));
  202. expect(decoder.readSplitFixed64(hexJoin)).toEqual(hexJoinHash(hashC));
  203. expect(decoder.readSplitFixed64(hexJoin)).toEqual(hexJoinHash(hashD));
  204. });
  205. });
  206. describe('sint64', function() {
  207. var /** !jspb.BinaryDecoder */ decoder;
  208. var hashA =
  209. String.fromCharCode(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00);
  210. var hashB =
  211. String.fromCharCode(0x12, 0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00);
  212. var hashC =
  213. String.fromCharCode(0x12, 0x34, 0x56, 0x78, 0x87, 0x65, 0x43, 0x21);
  214. var hashD =
  215. String.fromCharCode(0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF);
  216. beforeEach(function() {
  217. var encoder = new jspb.BinaryEncoder();
  218. encoder.writeZigzagVarintHash64(hashA);
  219. encoder.writeZigzagVarintHash64(hashB);
  220. encoder.writeZigzagVarintHash64(hashC);
  221. encoder.writeZigzagVarintHash64(hashD);
  222. decoder = jspb.BinaryDecoder.alloc(encoder.end());
  223. });
  224. it('reads 64-bit integers as decimal strings', function() {
  225. const signed = true;
  226. expect(decoder.readZigzagVarint64String())
  227. .toEqual(jspb.utils.hash64ToDecimalString(hashA, signed));
  228. expect(decoder.readZigzagVarint64String())
  229. .toEqual(jspb.utils.hash64ToDecimalString(hashB, signed));
  230. expect(decoder.readZigzagVarint64String())
  231. .toEqual(jspb.utils.hash64ToDecimalString(hashC, signed));
  232. expect(decoder.readZigzagVarint64String())
  233. .toEqual(jspb.utils.hash64ToDecimalString(hashD, signed));
  234. });
  235. it('reads 64-bit integers as hash strings', function() {
  236. expect(decoder.readZigzagVarintHash64()).toEqual(hashA);
  237. expect(decoder.readZigzagVarintHash64()).toEqual(hashB);
  238. expect(decoder.readZigzagVarintHash64()).toEqual(hashC);
  239. expect(decoder.readZigzagVarintHash64()).toEqual(hashD);
  240. });
  241. it('reads split 64 bit zigzag integers', function() {
  242. function hexJoin(bitsLow, bitsHigh) {
  243. return `0x${(bitsHigh >>> 0).toString(16)}:0x${
  244. (bitsLow >>> 0).toString(16)}`;
  245. }
  246. function hexJoinHash(hash64) {
  247. jspb.utils.splitHash64(hash64);
  248. return hexJoin(jspb.utils.split64Low, jspb.utils.split64High);
  249. }
  250. expect(decoder.readSplitZigzagVarint64(hexJoin))
  251. .toEqual(hexJoinHash(hashA));
  252. expect(decoder.readSplitZigzagVarint64(hexJoin))
  253. .toEqual(hexJoinHash(hashB));
  254. expect(decoder.readSplitZigzagVarint64(hexJoin))
  255. .toEqual(hexJoinHash(hashC));
  256. expect(decoder.readSplitZigzagVarint64(hexJoin))
  257. .toEqual(hexJoinHash(hashD));
  258. });
  259. it('does zigzag encoding properly', function() {
  260. // Test cases direcly from the protobuf dev guide.
  261. // https://engdoc.corp.google.com/eng/howto/protocolbuffers/developerguide/encoding.shtml?cl=head#types
  262. var testCases = [
  263. {original: '0', zigzag: '0'},
  264. {original: '-1', zigzag: '1'},
  265. {original: '1', zigzag: '2'},
  266. {original: '-2', zigzag: '3'},
  267. {original: '2147483647', zigzag: '4294967294'},
  268. {original: '-2147483648', zigzag: '4294967295'},
  269. // 64-bit extremes, not in dev guide.
  270. {original: '9223372036854775807', zigzag: '18446744073709551614'},
  271. {original: '-9223372036854775808', zigzag: '18446744073709551615'},
  272. ];
  273. var encoder = new jspb.BinaryEncoder();
  274. testCases.forEach(function(c) {
  275. encoder.writeZigzagVarint64String(c.original);
  276. });
  277. var buffer = encoder.end();
  278. var zigzagDecoder = jspb.BinaryDecoder.alloc(buffer);
  279. var varintDecoder = jspb.BinaryDecoder.alloc(buffer);
  280. testCases.forEach(function(c) {
  281. expect(zigzagDecoder.readZigzagVarint64String()).toEqual(c.original);
  282. expect(varintDecoder.readUnsignedVarint64String()).toEqual(c.zigzag);
  283. });
  284. });
  285. });
  286. /**
  287. * Tests reading and writing large strings
  288. */
  289. it('testLargeStrings', function() {
  290. var encoder = new jspb.BinaryEncoder();
  291. var len = 150000;
  292. var long_string = '';
  293. for (var i = 0; i < len; i++) {
  294. long_string += 'a';
  295. }
  296. encoder.writeString(long_string);
  297. var decoder = jspb.BinaryDecoder.alloc(encoder.end());
  298. assertEquals(long_string, decoder.readString(len));
  299. });
  300. /**
  301. * Test encoding and decoding utf-8.
  302. */
  303. it('testUtf8', function() {
  304. var encoder = new jspb.BinaryEncoder();
  305. var ascii = "ASCII should work in 3, 2, 1...";
  306. var utf8_two_bytes = "©";
  307. var utf8_three_bytes = "❄";
  308. var utf8_four_bytes = "😁";
  309. encoder.writeString(ascii);
  310. encoder.writeString(utf8_two_bytes);
  311. encoder.writeString(utf8_three_bytes);
  312. encoder.writeString(utf8_four_bytes);
  313. var decoder = jspb.BinaryDecoder.alloc(encoder.end());
  314. assertEquals(ascii, decoder.readString(ascii.length));
  315. assertEquals(utf8_two_bytes, decoder.readString(utf8_two_bytes.length));
  316. assertEquals(utf8_three_bytes, decoder.readString(utf8_three_bytes.length));
  317. assertEquals(utf8_four_bytes, decoder.readString(utf8_four_bytes.length));
  318. });
  319. /**
  320. * Verifies that misuse of the decoder class triggers assertions.
  321. */
  322. it('testDecodeErrors', function() {
  323. // Reading a value past the end of the stream should trigger an assertion.
  324. var decoder = jspb.BinaryDecoder.alloc([0, 1, 2]);
  325. assertThrows(function() {decoder.readUint64()});
  326. // Overlong varints should trigger assertions.
  327. decoder.setBlock([255, 255, 255, 255, 255, 255,
  328. 255, 255, 255, 255, 255, 0]);
  329. assertThrows(function() {decoder.readUnsignedVarint64()});
  330. decoder.reset();
  331. assertThrows(function() {decoder.readSignedVarint64()});
  332. decoder.reset();
  333. assertThrows(function() {decoder.readZigzagVarint64()});
  334. decoder.reset();
  335. assertThrows(function() {decoder.readUnsignedVarint32()});
  336. });
  337. /**
  338. * Tests encoding and decoding of unsigned integers.
  339. */
  340. it('testUnsignedIntegers', function() {
  341. doTestUnsignedValue(
  342. jspb.BinaryDecoder.prototype.readUint8,
  343. jspb.BinaryEncoder.prototype.writeUint8,
  344. 1, 0xFF, Math.round);
  345. doTestUnsignedValue(
  346. jspb.BinaryDecoder.prototype.readUint16,
  347. jspb.BinaryEncoder.prototype.writeUint16,
  348. 1, 0xFFFF, Math.round);
  349. doTestUnsignedValue(
  350. jspb.BinaryDecoder.prototype.readUint32,
  351. jspb.BinaryEncoder.prototype.writeUint32,
  352. 1, 0xFFFFFFFF, Math.round);
  353. doTestUnsignedValue(
  354. jspb.BinaryDecoder.prototype.readUint64,
  355. jspb.BinaryEncoder.prototype.writeUint64,
  356. 1, Math.pow(2, 64) - 1025, Math.round);
  357. });
  358. /**
  359. * Tests encoding and decoding of signed integers.
  360. */
  361. it('testSignedIntegers', function() {
  362. doTestSignedValue(
  363. jspb.BinaryDecoder.prototype.readInt8,
  364. jspb.BinaryEncoder.prototype.writeInt8,
  365. 1, -0x80, 0x7F, Math.round);
  366. doTestSignedValue(
  367. jspb.BinaryDecoder.prototype.readInt16,
  368. jspb.BinaryEncoder.prototype.writeInt16,
  369. 1, -0x8000, 0x7FFF, Math.round);
  370. doTestSignedValue(
  371. jspb.BinaryDecoder.prototype.readInt32,
  372. jspb.BinaryEncoder.prototype.writeInt32,
  373. 1, -0x80000000, 0x7FFFFFFF, Math.round);
  374. doTestSignedValue(
  375. jspb.BinaryDecoder.prototype.readInt64,
  376. jspb.BinaryEncoder.prototype.writeInt64,
  377. 1, -Math.pow(2, 63), Math.pow(2, 63) - 513, Math.round);
  378. });
  379. /**
  380. * Tests encoding and decoding of floats.
  381. */
  382. it('testFloats', function() {
  383. /**
  384. * @param {number} x
  385. * @return {number}
  386. */
  387. function truncate(x) {
  388. var temp = new Float32Array(1);
  389. temp[0] = x;
  390. return temp[0];
  391. }
  392. doTestSignedValue(
  393. jspb.BinaryDecoder.prototype.readFloat,
  394. jspb.BinaryEncoder.prototype.writeFloat,
  395. jspb.BinaryConstants.FLOAT32_EPS,
  396. -jspb.BinaryConstants.FLOAT32_MAX,
  397. jspb.BinaryConstants.FLOAT32_MAX,
  398. truncate);
  399. doTestSignedValue(
  400. jspb.BinaryDecoder.prototype.readDouble,
  401. jspb.BinaryEncoder.prototype.writeDouble,
  402. jspb.BinaryConstants.FLOAT64_EPS * 10,
  403. -jspb.BinaryConstants.FLOAT64_MAX,
  404. jspb.BinaryConstants.FLOAT64_MAX,
  405. function(x) { return x; });
  406. });
  407. });