decoder_test.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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. assertThrows(function() {writeValue.call(encoder, lowerLimit * 1.1);});
  125. assertThrows(function() {writeValue.call(encoder, upperLimit * 1.1);});
  126. }
  127. describe('binaryDecoderTest', function() {
  128. /**
  129. * Tests the decoder instance cache.
  130. */
  131. it('testInstanceCache', /** @suppress {visibility} */ function() {
  132. // Empty the instance caches.
  133. jspb.BinaryDecoder.instanceCache_ = [];
  134. // Allocating and then freeing a decoder should put it in the instance
  135. // cache.
  136. jspb.BinaryDecoder.alloc().free();
  137. assertEquals(1, jspb.BinaryDecoder.instanceCache_.length);
  138. // Allocating and then freeing three decoders should leave us with three in
  139. // the cache.
  140. var decoder1 = jspb.BinaryDecoder.alloc();
  141. var decoder2 = jspb.BinaryDecoder.alloc();
  142. var decoder3 = jspb.BinaryDecoder.alloc();
  143. decoder1.free();
  144. decoder2.free();
  145. decoder3.free();
  146. assertEquals(3, jspb.BinaryDecoder.instanceCache_.length);
  147. });
  148. describe('varint64', function() {
  149. var /** !jspb.BinaryEncoder */ encoder;
  150. var /** !jspb.BinaryDecoder */ decoder;
  151. var hashA = String.fromCharCode(0x00, 0x00, 0x00, 0x00,
  152. 0x00, 0x00, 0x00, 0x00);
  153. var hashB = String.fromCharCode(0x12, 0x34, 0x00, 0x00,
  154. 0x00, 0x00, 0x00, 0x00);
  155. var hashC = String.fromCharCode(0x12, 0x34, 0x56, 0x78,
  156. 0x87, 0x65, 0x43, 0x21);
  157. var hashD = String.fromCharCode(0xFF, 0xFF, 0xFF, 0xFF,
  158. 0xFF, 0xFF, 0xFF, 0xFF);
  159. beforeEach(function() {
  160. encoder = new jspb.BinaryEncoder();
  161. encoder.writeVarintHash64(hashA);
  162. encoder.writeVarintHash64(hashB);
  163. encoder.writeVarintHash64(hashC);
  164. encoder.writeVarintHash64(hashD);
  165. encoder.writeFixedHash64(hashA);
  166. encoder.writeFixedHash64(hashB);
  167. encoder.writeFixedHash64(hashC);
  168. encoder.writeFixedHash64(hashD);
  169. decoder = jspb.BinaryDecoder.alloc(encoder.end());
  170. });
  171. it('reads 64-bit integers as hash strings', function() {
  172. assertEquals(hashA, decoder.readVarintHash64());
  173. assertEquals(hashB, decoder.readVarintHash64());
  174. assertEquals(hashC, decoder.readVarintHash64());
  175. assertEquals(hashD, decoder.readVarintHash64());
  176. assertEquals(hashA, decoder.readFixedHash64());
  177. assertEquals(hashB, decoder.readFixedHash64());
  178. assertEquals(hashC, decoder.readFixedHash64());
  179. assertEquals(hashD, decoder.readFixedHash64());
  180. });
  181. it('reads split 64 bit integers', function() {
  182. function hexJoin(bitsLow, bitsHigh) {
  183. return `0x${(bitsHigh >>> 0).toString(16)}:0x${
  184. (bitsLow >>> 0).toString(16)}`;
  185. }
  186. function hexJoinHash(hash64) {
  187. jspb.utils.splitHash64(hash64);
  188. return hexJoin(jspb.utils.split64Low, jspb.utils.split64High);
  189. }
  190. expect(decoder.readSplitVarint64(hexJoin)).toEqual(hexJoinHash(hashA));
  191. expect(decoder.readSplitVarint64(hexJoin)).toEqual(hexJoinHash(hashB));
  192. expect(decoder.readSplitVarint64(hexJoin)).toEqual(hexJoinHash(hashC));
  193. expect(decoder.readSplitVarint64(hexJoin)).toEqual(hexJoinHash(hashD));
  194. expect(decoder.readSplitFixed64(hexJoin)).toEqual(hexJoinHash(hashA));
  195. expect(decoder.readSplitFixed64(hexJoin)).toEqual(hexJoinHash(hashB));
  196. expect(decoder.readSplitFixed64(hexJoin)).toEqual(hexJoinHash(hashC));
  197. expect(decoder.readSplitFixed64(hexJoin)).toEqual(hexJoinHash(hashD));
  198. });
  199. });
  200. describe('sint64', function() {
  201. var /** !jspb.BinaryDecoder */ decoder;
  202. var hashA =
  203. String.fromCharCode(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00);
  204. var hashB =
  205. String.fromCharCode(0x12, 0x34, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00);
  206. var hashC =
  207. String.fromCharCode(0x12, 0x34, 0x56, 0x78, 0x87, 0x65, 0x43, 0x21);
  208. var hashD =
  209. String.fromCharCode(0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF);
  210. beforeEach(function() {
  211. var encoder = new jspb.BinaryEncoder();
  212. encoder.writeZigzagVarintHash64(hashA);
  213. encoder.writeZigzagVarintHash64(hashB);
  214. encoder.writeZigzagVarintHash64(hashC);
  215. encoder.writeZigzagVarintHash64(hashD);
  216. decoder = jspb.BinaryDecoder.alloc(encoder.end());
  217. });
  218. it('reads 64-bit integers as decimal strings', function() {
  219. const signed = true;
  220. expect(decoder.readZigzagVarint64String())
  221. .toEqual(jspb.utils.hash64ToDecimalString(hashA, signed));
  222. expect(decoder.readZigzagVarint64String())
  223. .toEqual(jspb.utils.hash64ToDecimalString(hashB, signed));
  224. expect(decoder.readZigzagVarint64String())
  225. .toEqual(jspb.utils.hash64ToDecimalString(hashC, signed));
  226. expect(decoder.readZigzagVarint64String())
  227. .toEqual(jspb.utils.hash64ToDecimalString(hashD, signed));
  228. });
  229. it('reads 64-bit integers as hash strings', function() {
  230. expect(decoder.readZigzagVarintHash64()).toEqual(hashA);
  231. expect(decoder.readZigzagVarintHash64()).toEqual(hashB);
  232. expect(decoder.readZigzagVarintHash64()).toEqual(hashC);
  233. expect(decoder.readZigzagVarintHash64()).toEqual(hashD);
  234. });
  235. it('reads split 64 bit zigzag integers', function() {
  236. function hexJoin(bitsLow, bitsHigh) {
  237. return `0x${(bitsHigh >>> 0).toString(16)}:0x${
  238. (bitsLow >>> 0).toString(16)}`;
  239. }
  240. function hexJoinHash(hash64) {
  241. jspb.utils.splitHash64(hash64);
  242. return hexJoin(jspb.utils.split64Low, jspb.utils.split64High);
  243. }
  244. expect(decoder.readSplitZigzagVarint64(hexJoin))
  245. .toEqual(hexJoinHash(hashA));
  246. expect(decoder.readSplitZigzagVarint64(hexJoin))
  247. .toEqual(hexJoinHash(hashB));
  248. expect(decoder.readSplitZigzagVarint64(hexJoin))
  249. .toEqual(hexJoinHash(hashC));
  250. expect(decoder.readSplitZigzagVarint64(hexJoin))
  251. .toEqual(hexJoinHash(hashD));
  252. });
  253. it('does zigzag encoding properly', function() {
  254. // Test cases direcly from the protobuf dev guide.
  255. // https://engdoc.corp.google.com/eng/howto/protocolbuffers/developerguide/encoding.shtml?cl=head#types
  256. var testCases = [
  257. {original: '0', zigzag: '0'},
  258. {original: '-1', zigzag: '1'},
  259. {original: '1', zigzag: '2'},
  260. {original: '-2', zigzag: '3'},
  261. {original: '2147483647', zigzag: '4294967294'},
  262. {original: '-2147483648', zigzag: '4294967295'},
  263. // 64-bit extremes, not in dev guide.
  264. {original: '9223372036854775807', zigzag: '18446744073709551614'},
  265. {original: '-9223372036854775808', zigzag: '18446744073709551615'},
  266. ];
  267. var encoder = new jspb.BinaryEncoder();
  268. testCases.forEach(function(c) {
  269. encoder.writeZigzagVarint64String(c.original);
  270. });
  271. var buffer = encoder.end();
  272. var zigzagDecoder = jspb.BinaryDecoder.alloc(buffer);
  273. var varintDecoder = jspb.BinaryDecoder.alloc(buffer);
  274. testCases.forEach(function(c) {
  275. expect(zigzagDecoder.readZigzagVarint64String()).toEqual(c.original);
  276. expect(varintDecoder.readUnsignedVarint64String()).toEqual(c.zigzag);
  277. });
  278. });
  279. });
  280. /**
  281. * Tests reading and writing large strings
  282. */
  283. it('testLargeStrings', function() {
  284. var encoder = new jspb.BinaryEncoder();
  285. var len = 150000;
  286. var long_string = '';
  287. for (var i = 0; i < len; i++) {
  288. long_string += 'a';
  289. }
  290. encoder.writeString(long_string);
  291. var decoder = jspb.BinaryDecoder.alloc(encoder.end());
  292. assertEquals(long_string, decoder.readString(len));
  293. });
  294. /**
  295. * Test encoding and decoding utf-8.
  296. */
  297. it('testUtf8', function() {
  298. var encoder = new jspb.BinaryEncoder();
  299. var ascii = "ASCII should work in 3, 2, 1...";
  300. var utf8_two_bytes = "©";
  301. var utf8_three_bytes = "❄";
  302. var utf8_four_bytes = "😁";
  303. encoder.writeString(ascii);
  304. encoder.writeString(utf8_two_bytes);
  305. encoder.writeString(utf8_three_bytes);
  306. encoder.writeString(utf8_four_bytes);
  307. var decoder = jspb.BinaryDecoder.alloc(encoder.end());
  308. assertEquals(ascii, decoder.readString(ascii.length));
  309. assertEquals(utf8_two_bytes, decoder.readString(utf8_two_bytes.length));
  310. assertEquals(utf8_three_bytes, decoder.readString(utf8_three_bytes.length));
  311. assertEquals(utf8_four_bytes, decoder.readString(utf8_four_bytes.length));
  312. });
  313. /**
  314. * Verifies that misuse of the decoder class triggers assertions.
  315. */
  316. it('testDecodeErrors', function() {
  317. // Reading a value past the end of the stream should trigger an assertion.
  318. var decoder = jspb.BinaryDecoder.alloc([0, 1, 2]);
  319. assertThrows(function() {decoder.readUint64()});
  320. // Overlong varints should trigger assertions.
  321. decoder.setBlock([255, 255, 255, 255, 255, 255,
  322. 255, 255, 255, 255, 255, 0]);
  323. assertThrows(function() {decoder.readUnsignedVarint64()});
  324. decoder.reset();
  325. assertThrows(function() {decoder.readSignedVarint64()});
  326. decoder.reset();
  327. assertThrows(function() {decoder.readZigzagVarint64()});
  328. decoder.reset();
  329. assertThrows(function() {decoder.readUnsignedVarint32()});
  330. });
  331. /**
  332. * Tests encoding and decoding of unsigned integers.
  333. */
  334. it('testUnsignedIntegers', function() {
  335. doTestUnsignedValue(
  336. jspb.BinaryDecoder.prototype.readUint8,
  337. jspb.BinaryEncoder.prototype.writeUint8,
  338. 1, 0xFF, Math.round);
  339. doTestUnsignedValue(
  340. jspb.BinaryDecoder.prototype.readUint16,
  341. jspb.BinaryEncoder.prototype.writeUint16,
  342. 1, 0xFFFF, Math.round);
  343. doTestUnsignedValue(
  344. jspb.BinaryDecoder.prototype.readUint32,
  345. jspb.BinaryEncoder.prototype.writeUint32,
  346. 1, 0xFFFFFFFF, Math.round);
  347. doTestUnsignedValue(
  348. jspb.BinaryDecoder.prototype.readUint64,
  349. jspb.BinaryEncoder.prototype.writeUint64,
  350. 1, Math.pow(2, 64) - 1025, Math.round);
  351. });
  352. /**
  353. * Tests encoding and decoding of signed integers.
  354. */
  355. it('testSignedIntegers', function() {
  356. doTestSignedValue(
  357. jspb.BinaryDecoder.prototype.readInt8,
  358. jspb.BinaryEncoder.prototype.writeInt8,
  359. 1, -0x80, 0x7F, Math.round);
  360. doTestSignedValue(
  361. jspb.BinaryDecoder.prototype.readInt16,
  362. jspb.BinaryEncoder.prototype.writeInt16,
  363. 1, -0x8000, 0x7FFF, Math.round);
  364. doTestSignedValue(
  365. jspb.BinaryDecoder.prototype.readInt32,
  366. jspb.BinaryEncoder.prototype.writeInt32,
  367. 1, -0x80000000, 0x7FFFFFFF, Math.round);
  368. doTestSignedValue(
  369. jspb.BinaryDecoder.prototype.readInt64,
  370. jspb.BinaryEncoder.prototype.writeInt64,
  371. 1, -Math.pow(2, 63), Math.pow(2, 63) - 513, Math.round);
  372. });
  373. /**
  374. * Tests encoding and decoding of floats.
  375. */
  376. it('testFloats', function() {
  377. /**
  378. * @param {number} x
  379. * @return {number}
  380. */
  381. function truncate(x) {
  382. var temp = new Float32Array(1);
  383. temp[0] = x;
  384. return temp[0];
  385. }
  386. doTestSignedValue(
  387. jspb.BinaryDecoder.prototype.readFloat,
  388. jspb.BinaryEncoder.prototype.writeFloat,
  389. jspb.BinaryConstants.FLOAT32_EPS,
  390. -jspb.BinaryConstants.FLOAT32_MAX,
  391. jspb.BinaryConstants.FLOAT32_MAX,
  392. truncate);
  393. doTestSignedValue(
  394. jspb.BinaryDecoder.prototype.readDouble,
  395. jspb.BinaryEncoder.prototype.writeDouble,
  396. jspb.BinaryConstants.FLOAT64_EPS * 10,
  397. -jspb.BinaryConstants.FLOAT64_MAX,
  398. jspb.BinaryConstants.FLOAT64_MAX,
  399. function(x) { return x; });
  400. });
  401. });