decoder_test.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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. /**
  201. * Tests reading and writing large strings
  202. */
  203. it('testLargeStrings', function() {
  204. var encoder = new jspb.BinaryEncoder();
  205. var len = 150000;
  206. var long_string = '';
  207. for (var i = 0; i < len; i++) {
  208. long_string += 'a';
  209. }
  210. encoder.writeString(long_string);
  211. var decoder = jspb.BinaryDecoder.alloc(encoder.end());
  212. assertEquals(long_string, decoder.readString(len));
  213. });
  214. /**
  215. * Test encoding and decoding utf-8.
  216. */
  217. it('testUtf8', function() {
  218. var encoder = new jspb.BinaryEncoder();
  219. var ascii = "ASCII should work in 3, 2, 1...";
  220. var utf8_two_bytes = "©";
  221. var utf8_three_bytes = "❄";
  222. var utf8_four_bytes = "😁";
  223. encoder.writeString(ascii);
  224. encoder.writeString(utf8_two_bytes);
  225. encoder.writeString(utf8_three_bytes);
  226. encoder.writeString(utf8_four_bytes);
  227. var decoder = jspb.BinaryDecoder.alloc(encoder.end());
  228. assertEquals(ascii, decoder.readString(ascii.length));
  229. assertEquals(utf8_two_bytes, decoder.readString(utf8_two_bytes.length));
  230. assertEquals(utf8_three_bytes, decoder.readString(utf8_three_bytes.length));
  231. assertEquals(utf8_four_bytes, decoder.readString(utf8_four_bytes.length));
  232. });
  233. /**
  234. * Verifies that misuse of the decoder class triggers assertions.
  235. */
  236. it('testDecodeErrors', function() {
  237. // Reading a value past the end of the stream should trigger an assertion.
  238. var decoder = jspb.BinaryDecoder.alloc([0, 1, 2]);
  239. assertThrows(function() {decoder.readUint64()});
  240. // Overlong varints should trigger assertions.
  241. decoder.setBlock([255, 255, 255, 255, 255, 255,
  242. 255, 255, 255, 255, 255, 0]);
  243. assertThrows(function() {decoder.readUnsignedVarint64()});
  244. decoder.reset();
  245. assertThrows(function() {decoder.readSignedVarint64()});
  246. decoder.reset();
  247. assertThrows(function() {decoder.readZigzagVarint64()});
  248. decoder.reset();
  249. assertThrows(function() {decoder.readUnsignedVarint32()});
  250. });
  251. /**
  252. * Tests encoding and decoding of unsigned integers.
  253. */
  254. it('testUnsignedIntegers', function() {
  255. doTestUnsignedValue(
  256. jspb.BinaryDecoder.prototype.readUint8,
  257. jspb.BinaryEncoder.prototype.writeUint8,
  258. 1, 0xFF, Math.round);
  259. doTestUnsignedValue(
  260. jspb.BinaryDecoder.prototype.readUint16,
  261. jspb.BinaryEncoder.prototype.writeUint16,
  262. 1, 0xFFFF, Math.round);
  263. doTestUnsignedValue(
  264. jspb.BinaryDecoder.prototype.readUint32,
  265. jspb.BinaryEncoder.prototype.writeUint32,
  266. 1, 0xFFFFFFFF, Math.round);
  267. doTestUnsignedValue(
  268. jspb.BinaryDecoder.prototype.readUint64,
  269. jspb.BinaryEncoder.prototype.writeUint64,
  270. 1, Math.pow(2, 64) - 1025, Math.round);
  271. });
  272. /**
  273. * Tests encoding and decoding of signed integers.
  274. */
  275. it('testSignedIntegers', function() {
  276. doTestSignedValue(
  277. jspb.BinaryDecoder.prototype.readInt8,
  278. jspb.BinaryEncoder.prototype.writeInt8,
  279. 1, -0x80, 0x7F, Math.round);
  280. doTestSignedValue(
  281. jspb.BinaryDecoder.prototype.readInt16,
  282. jspb.BinaryEncoder.prototype.writeInt16,
  283. 1, -0x8000, 0x7FFF, Math.round);
  284. doTestSignedValue(
  285. jspb.BinaryDecoder.prototype.readInt32,
  286. jspb.BinaryEncoder.prototype.writeInt32,
  287. 1, -0x80000000, 0x7FFFFFFF, Math.round);
  288. doTestSignedValue(
  289. jspb.BinaryDecoder.prototype.readInt64,
  290. jspb.BinaryEncoder.prototype.writeInt64,
  291. 1, -Math.pow(2, 63), Math.pow(2, 63) - 513, Math.round);
  292. });
  293. /**
  294. * Tests encoding and decoding of floats.
  295. */
  296. it('testFloats', function() {
  297. /**
  298. * @param {number} x
  299. * @return {number}
  300. */
  301. function truncate(x) {
  302. var temp = new Float32Array(1);
  303. temp[0] = x;
  304. return temp[0];
  305. }
  306. doTestSignedValue(
  307. jspb.BinaryDecoder.prototype.readFloat,
  308. jspb.BinaryEncoder.prototype.writeFloat,
  309. jspb.BinaryConstants.FLOAT32_EPS,
  310. -jspb.BinaryConstants.FLOAT32_MAX,
  311. jspb.BinaryConstants.FLOAT32_MAX,
  312. truncate);
  313. doTestSignedValue(
  314. jspb.BinaryDecoder.prototype.readDouble,
  315. jspb.BinaryEncoder.prototype.writeDouble,
  316. jspb.BinaryConstants.FLOAT64_EPS * 10,
  317. -jspb.BinaryConstants.FLOAT64_MAX,
  318. jspb.BinaryConstants.FLOAT64_MAX,
  319. function(x) { return x; });
  320. });
  321. });