decoder.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950
  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 utilities for decoding primitive values
  32. * (signed and unsigned integers, varints, booleans, enums, hashes, strings,
  33. * and raw bytes) embedded in Uint8Arrays into their corresponding Javascript
  34. * types.
  35. *
  36. * Major caveat - Javascript is unable to accurately represent integers larger
  37. * than 2^53 due to its use of a double-precision floating point format or all
  38. * numbers. If you need to guarantee that 64-bit values survive with all bits
  39. * intact, you _must_ read them using one of the Hash64 methods, which return
  40. * an 8-character string.
  41. *
  42. * @author aappleby@google.com (Austin Appleby)
  43. */
  44. goog.provide('jspb.BinaryDecoder');
  45. goog.require('goog.asserts');
  46. goog.require('goog.crypt');
  47. goog.require('jspb.utils');
  48. /**
  49. * BinaryDecoder implements the decoders for all the wire types specified in
  50. * https://developers.google.com/protocol-buffers/docs/encoding.
  51. *
  52. * @param {jspb.ByteSource=} opt_bytes The bytes we're reading from.
  53. * @param {number=} opt_start The optional offset to start reading at.
  54. * @param {number=} opt_length The optional length of the block to read -
  55. * we'll throw an assertion if we go off the end of the block.
  56. * @constructor
  57. * @struct
  58. */
  59. jspb.BinaryDecoder = function(opt_bytes, opt_start, opt_length) {
  60. /**
  61. * Typed byte-wise view of the source buffer.
  62. * @private {?Uint8Array}
  63. */
  64. this.bytes_ = null;
  65. /**
  66. * Start point of the block to read.
  67. * @private {number}
  68. */
  69. this.start_ = 0;
  70. /**
  71. * End point of the block to read.
  72. * @private {number}
  73. */
  74. this.end_ = 0;
  75. /**
  76. * Current read location in bytes_.
  77. * @private {number}
  78. */
  79. this.cursor_ = 0;
  80. /**
  81. * Set to true if this decoder encountered an error due to corrupt data.
  82. * @private {boolean}
  83. */
  84. this.error_ = false;
  85. if (opt_bytes) {
  86. this.setBlock(opt_bytes, opt_start, opt_length);
  87. }
  88. };
  89. /**
  90. * Global pool of BinaryDecoder instances.
  91. * @private {!Array<!jspb.BinaryDecoder>}
  92. */
  93. jspb.BinaryDecoder.instanceCache_ = [];
  94. /**
  95. * Pops an instance off the instance cache, or creates one if the cache is
  96. * empty.
  97. * @param {jspb.ByteSource=} opt_bytes The bytes we're reading from.
  98. * @param {number=} opt_start The optional offset to start reading at.
  99. * @param {number=} opt_length The optional length of the block to read -
  100. * we'll throw an assertion if we go off the end of the block.
  101. * @return {!jspb.BinaryDecoder}
  102. */
  103. jspb.BinaryDecoder.alloc = function(opt_bytes, opt_start, opt_length) {
  104. if (jspb.BinaryDecoder.instanceCache_.length) {
  105. var newDecoder = jspb.BinaryDecoder.instanceCache_.pop();
  106. if (opt_bytes) {
  107. newDecoder.setBlock(opt_bytes, opt_start, opt_length);
  108. }
  109. return newDecoder;
  110. } else {
  111. return new jspb.BinaryDecoder(opt_bytes, opt_start, opt_length);
  112. }
  113. };
  114. /**
  115. * Puts this instance back in the instance cache.
  116. */
  117. jspb.BinaryDecoder.prototype.free = function() {
  118. this.clear();
  119. if (jspb.BinaryDecoder.instanceCache_.length < 100) {
  120. jspb.BinaryDecoder.instanceCache_.push(this);
  121. }
  122. };
  123. /**
  124. * Makes a copy of this decoder.
  125. * @return {!jspb.BinaryDecoder}
  126. */
  127. jspb.BinaryDecoder.prototype.clone = function() {
  128. return jspb.BinaryDecoder.alloc(this.bytes_,
  129. this.start_, this.end_ - this.start_);
  130. };
  131. /**
  132. * Clears the decoder.
  133. */
  134. jspb.BinaryDecoder.prototype.clear = function() {
  135. this.bytes_ = null;
  136. this.start_ = 0;
  137. this.end_ = 0;
  138. this.cursor_ = 0;
  139. this.error_ = false;
  140. };
  141. /**
  142. * Returns the raw buffer.
  143. * @return {?Uint8Array} The raw buffer.
  144. */
  145. jspb.BinaryDecoder.prototype.getBuffer = function() {
  146. return this.bytes_;
  147. };
  148. /**
  149. * Changes the block of bytes we're decoding.
  150. * @param {!jspb.ByteSource} data The bytes we're reading from.
  151. * @param {number=} opt_start The optional offset to start reading at.
  152. * @param {number=} opt_length The optional length of the block to read -
  153. * we'll throw an assertion if we go off the end of the block.
  154. */
  155. jspb.BinaryDecoder.prototype.setBlock =
  156. function(data, opt_start, opt_length) {
  157. this.bytes_ = jspb.utils.byteSourceToUint8Array(data);
  158. this.start_ = (opt_start !== undefined) ? opt_start : 0;
  159. this.end_ = (opt_length !== undefined) ? this.start_ + opt_length :
  160. this.bytes_.length;
  161. this.cursor_ = this.start_;
  162. };
  163. /**
  164. * @return {number}
  165. */
  166. jspb.BinaryDecoder.prototype.getEnd = function() {
  167. return this.end_;
  168. };
  169. /**
  170. * @param {number} end
  171. */
  172. jspb.BinaryDecoder.prototype.setEnd = function(end) {
  173. this.end_ = end;
  174. };
  175. /**
  176. * Moves the read cursor back to the start of the block.
  177. */
  178. jspb.BinaryDecoder.prototype.reset = function() {
  179. this.cursor_ = this.start_;
  180. };
  181. /**
  182. * Returns the internal read cursor.
  183. * @return {number} The internal read cursor.
  184. */
  185. jspb.BinaryDecoder.prototype.getCursor = function() {
  186. return this.cursor_;
  187. };
  188. /**
  189. * Returns the internal read cursor.
  190. * @param {number} cursor The new cursor.
  191. */
  192. jspb.BinaryDecoder.prototype.setCursor = function(cursor) {
  193. this.cursor_ = cursor;
  194. };
  195. /**
  196. * Advances the stream cursor by the given number of bytes.
  197. * @param {number} count The number of bytes to advance by.
  198. */
  199. jspb.BinaryDecoder.prototype.advance = function(count) {
  200. this.cursor_ += count;
  201. goog.asserts.assert(this.cursor_ <= this.end_);
  202. };
  203. /**
  204. * Returns true if this decoder is at the end of the block.
  205. * @return {boolean}
  206. */
  207. jspb.BinaryDecoder.prototype.atEnd = function() {
  208. return this.cursor_ == this.end_;
  209. };
  210. /**
  211. * Returns true if this decoder is at the end of the block.
  212. * @return {boolean}
  213. */
  214. jspb.BinaryDecoder.prototype.pastEnd = function() {
  215. return this.cursor_ > this.end_;
  216. };
  217. /**
  218. * Returns true if this decoder encountered an error due to corrupt data.
  219. * @return {boolean}
  220. */
  221. jspb.BinaryDecoder.prototype.getError = function() {
  222. return this.error_ ||
  223. (this.cursor_ < 0) ||
  224. (this.cursor_ > this.end_);
  225. };
  226. /**
  227. * Reads an unsigned varint from the binary stream and invokes the conversion
  228. * function with the value in two signed 32 bit integers to produce the result.
  229. * Since this does not convert the value to a number, no precision is lost.
  230. *
  231. * It's possible for an unsigned varint to be incorrectly encoded - more than
  232. * 64 bits' worth of data could be present. If this happens, this method will
  233. * throw an error.
  234. *
  235. * Decoding varints requires doing some funny base-128 math - for more
  236. * details on the format, see
  237. * https://developers.google.com/protocol-buffers/docs/encoding
  238. *
  239. * @param {function(number, number): T} convert Conversion function to produce
  240. * the result value, takes parameters (lowBits, highBits).
  241. * @return {T}
  242. * @template T
  243. */
  244. jspb.BinaryDecoder.prototype.readSplitVarint64 = function(convert) {
  245. var temp = 128;
  246. var lowBits = 0;
  247. var highBits = 0;
  248. // Read the first four bytes of the varint, stopping at the terminator if we
  249. // see it.
  250. for (var i = 0; i < 4 && temp >= 128; i++) {
  251. temp = this.bytes_[this.cursor_++];
  252. lowBits |= (temp & 0x7F) << (i * 7);
  253. }
  254. if (temp >= 128) {
  255. // Read the fifth byte, which straddles the low and high dwords.
  256. temp = this.bytes_[this.cursor_++];
  257. lowBits |= (temp & 0x7F) << 28;
  258. highBits |= (temp & 0x7F) >> 4;
  259. }
  260. if (temp >= 128) {
  261. // Read the sixth through tenth byte.
  262. for (var i = 0; i < 5 && temp >= 128; i++) {
  263. temp = this.bytes_[this.cursor_++];
  264. highBits |= (temp & 0x7F) << (i * 7 + 3);
  265. }
  266. }
  267. if (temp < 128) {
  268. return convert(lowBits >>> 0, highBits >>> 0);
  269. }
  270. // If we did not see the terminator, the encoding was invalid.
  271. goog.asserts.fail('Failed to read varint, encoding is invalid.');
  272. this.error_ = true;
  273. };
  274. /**
  275. * Reads a signed zigzag encoded varint from the binary stream and invokes
  276. * the conversion function with the value in two signed 32 bit integers to
  277. * produce the result. Since this does not convert the value to a number, no
  278. * precision is lost.
  279. *
  280. * It's possible for an unsigned varint to be incorrectly encoded - more than
  281. * 64 bits' worth of data could be present. If this happens, this method will
  282. * throw an error.
  283. *
  284. * Zigzag encoding is a modification of varint encoding that reduces the
  285. * storage overhead for small negative integers - for more details on the
  286. * format, see https://developers.google.com/protocol-buffers/docs/encoding
  287. *
  288. * @param {function(number, number): T} convert Conversion function to produce
  289. * the result value, takes parameters (lowBits, highBits).
  290. * @return {T}
  291. * @template T
  292. */
  293. jspb.BinaryDecoder.prototype.readSplitZigzagVarint64 = function(convert) {
  294. return this.readSplitVarint64(function(low, high) {
  295. return jspb.utils.fromZigzag64(low, high, convert);
  296. });
  297. };
  298. /**
  299. * Reads a 64-bit fixed-width value from the stream and invokes the conversion
  300. * function with the value in two signed 32 bit integers to produce the result.
  301. * Since this does not convert the value to a number, no precision is lost.
  302. *
  303. * @param {function(number, number): T} convert Conversion function to produce
  304. * the result value, takes parameters (lowBits, highBits).
  305. * @return {T}
  306. * @template T
  307. */
  308. jspb.BinaryDecoder.prototype.readSplitFixed64 = function(convert) {
  309. var bytes = this.bytes_;
  310. var cursor = this.cursor_;
  311. this.cursor_ += 8;
  312. var lowBits = 0;
  313. var highBits = 0;
  314. for (var i = cursor + 7; i >= cursor; i--) {
  315. lowBits = (lowBits << 8) | bytes[i];
  316. highBits = (highBits << 8) | bytes[i + 4];
  317. }
  318. return convert(lowBits, highBits);
  319. };
  320. /**
  321. * Skips over a varint in the block without decoding it.
  322. */
  323. jspb.BinaryDecoder.prototype.skipVarint = function() {
  324. while (this.bytes_[this.cursor_] & 0x80) {
  325. this.cursor_++;
  326. }
  327. this.cursor_++;
  328. };
  329. /**
  330. * Skips backwards over a varint in the block - to do this correctly, we have
  331. * to know the value we're skipping backwards over or things are ambiguous.
  332. * @param {number} value The varint value to unskip.
  333. */
  334. jspb.BinaryDecoder.prototype.unskipVarint = function(value) {
  335. while (value > 128) {
  336. this.cursor_--;
  337. value = value >>> 7;
  338. }
  339. this.cursor_--;
  340. };
  341. /**
  342. * Reads a 32-bit varint from the binary stream. Due to a quirk of the encoding
  343. * format and Javascript's handling of bitwise math, this actually works
  344. * correctly for both signed and unsigned 32-bit varints.
  345. *
  346. * This function is called vastly more frequently than any other in
  347. * BinaryDecoder, so it has been unrolled and tweaked for performance.
  348. *
  349. * If there are more than 32 bits of data in the varint, it _must_ be due to
  350. * sign-extension. If we're in debug mode and the high 32 bits don't match the
  351. * expected sign extension, this method will throw an error.
  352. *
  353. * Decoding varints requires doing some funny base-128 math - for more
  354. * details on the format, see
  355. * https://developers.google.com/protocol-buffers/docs/encoding
  356. *
  357. * @return {number} The decoded unsigned 32-bit varint.
  358. */
  359. jspb.BinaryDecoder.prototype.readUnsignedVarint32 = function() {
  360. var temp;
  361. var bytes = this.bytes_;
  362. temp = bytes[this.cursor_ + 0];
  363. var x = (temp & 0x7F);
  364. if (temp < 128) {
  365. this.cursor_ += 1;
  366. goog.asserts.assert(this.cursor_ <= this.end_);
  367. return x;
  368. }
  369. temp = bytes[this.cursor_ + 1];
  370. x |= (temp & 0x7F) << 7;
  371. if (temp < 128) {
  372. this.cursor_ += 2;
  373. goog.asserts.assert(this.cursor_ <= this.end_);
  374. return x;
  375. }
  376. temp = bytes[this.cursor_ + 2];
  377. x |= (temp & 0x7F) << 14;
  378. if (temp < 128) {
  379. this.cursor_ += 3;
  380. goog.asserts.assert(this.cursor_ <= this.end_);
  381. return x;
  382. }
  383. temp = bytes[this.cursor_ + 3];
  384. x |= (temp & 0x7F) << 21;
  385. if (temp < 128) {
  386. this.cursor_ += 4;
  387. goog.asserts.assert(this.cursor_ <= this.end_);
  388. return x;
  389. }
  390. temp = bytes[this.cursor_ + 4];
  391. x |= (temp & 0x0F) << 28;
  392. if (temp < 128) {
  393. // We're reading the high bits of an unsigned varint. The byte we just read
  394. // also contains bits 33 through 35, which we're going to discard.
  395. this.cursor_ += 5;
  396. goog.asserts.assert(this.cursor_ <= this.end_);
  397. return x >>> 0;
  398. }
  399. // If we get here, we need to truncate coming bytes. However we need to make
  400. // sure cursor place is correct.
  401. this.cursor_ += 5;
  402. if (bytes[this.cursor_++] >= 128 &&
  403. bytes[this.cursor_++] >= 128 &&
  404. bytes[this.cursor_++] >= 128 &&
  405. bytes[this.cursor_++] >= 128 &&
  406. bytes[this.cursor_++] >= 128) {
  407. // If we get here, the varint is too long.
  408. goog.asserts.assert(false);
  409. }
  410. goog.asserts.assert(this.cursor_ <= this.end_);
  411. return x;
  412. };
  413. /**
  414. * The readUnsignedVarint32 above deals with signed 32-bit varints correctly,
  415. * so this is just an alias.
  416. *
  417. * @return {number} The decoded signed 32-bit varint.
  418. */
  419. jspb.BinaryDecoder.prototype.readSignedVarint32 =
  420. jspb.BinaryDecoder.prototype.readUnsignedVarint32;
  421. /**
  422. * Reads a 32-bit unsigned variant and returns its value as a string.
  423. *
  424. * @return {string} The decoded unsigned 32-bit varint as a string.
  425. */
  426. jspb.BinaryDecoder.prototype.readUnsignedVarint32String = function() {
  427. // 32-bit integers fit in JavaScript numbers without loss of precision, so
  428. // string variants of 32-bit varint readers can simply delegate then convert
  429. // to string.
  430. var value = this.readUnsignedVarint32();
  431. return value.toString();
  432. };
  433. /**
  434. * Reads a 32-bit signed variant and returns its value as a string.
  435. *
  436. * @return {string} The decoded signed 32-bit varint as a string.
  437. */
  438. jspb.BinaryDecoder.prototype.readSignedVarint32String = function() {
  439. // 32-bit integers fit in JavaScript numbers without loss of precision, so
  440. // string variants of 32-bit varint readers can simply delegate then convert
  441. // to string.
  442. var value = this.readSignedVarint32();
  443. return value.toString();
  444. };
  445. /**
  446. * Reads a signed, zigzag-encoded 32-bit varint from the binary stream.
  447. *
  448. * Zigzag encoding is a modification of varint encoding that reduces the
  449. * storage overhead for small negative integers - for more details on the
  450. * format, see https://developers.google.com/protocol-buffers/docs/encoding
  451. *
  452. * @return {number} The decoded signed, zigzag-encoded 32-bit varint.
  453. */
  454. jspb.BinaryDecoder.prototype.readZigzagVarint32 = function() {
  455. var result = this.readUnsignedVarint32();
  456. return (result >>> 1) ^ - (result & 1);
  457. };
  458. /**
  459. * Reads an unsigned 64-bit varint from the binary stream. Note that since
  460. * Javascript represents all numbers as double-precision floats, there will be
  461. * precision lost if the absolute value of the varint is larger than 2^53.
  462. *
  463. * @return {number} The decoded unsigned varint. Precision will be lost if the
  464. * integer exceeds 2^53.
  465. */
  466. jspb.BinaryDecoder.prototype.readUnsignedVarint64 = function() {
  467. return this.readSplitVarint64(jspb.utils.joinUint64);
  468. };
  469. /**
  470. * Reads an unsigned 64-bit varint from the binary stream and returns the value
  471. * as a decimal string.
  472. *
  473. * @return {string} The decoded unsigned varint as a decimal string.
  474. */
  475. jspb.BinaryDecoder.prototype.readUnsignedVarint64String = function() {
  476. return this.readSplitVarint64(jspb.utils.joinUnsignedDecimalString);
  477. };
  478. /**
  479. * Reads a signed 64-bit varint from the binary stream. Note that since
  480. * Javascript represents all numbers as double-precision floats, there will be
  481. * precision lost if the absolute value of the varint is larger than 2^53.
  482. *
  483. * @return {number} The decoded signed varint. Precision will be lost if the
  484. * integer exceeds 2^53.
  485. */
  486. jspb.BinaryDecoder.prototype.readSignedVarint64 = function() {
  487. return this.readSplitVarint64(jspb.utils.joinInt64);
  488. };
  489. /**
  490. * Reads an signed 64-bit varint from the binary stream and returns the value
  491. * as a decimal string.
  492. *
  493. * @return {string} The decoded signed varint as a decimal string.
  494. */
  495. jspb.BinaryDecoder.prototype.readSignedVarint64String = function() {
  496. return this.readSplitVarint64(jspb.utils.joinSignedDecimalString);
  497. };
  498. /**
  499. * Reads a signed, zigzag-encoded 64-bit varint from the binary stream. Note
  500. * that since Javascript represents all numbers as double-precision floats,
  501. * there will be precision lost if the absolute value of the varint is larger
  502. * than 2^53.
  503. *
  504. * Zigzag encoding is a modification of varint encoding that reduces the
  505. * storage overhead for small negative integers - for more details on the
  506. * format, see https://developers.google.com/protocol-buffers/docs/encoding
  507. *
  508. * @return {number} The decoded zigzag varint. Precision will be lost if the
  509. * integer exceeds 2^53.
  510. */
  511. jspb.BinaryDecoder.prototype.readZigzagVarint64 = function() {
  512. return this.readSplitVarint64(jspb.utils.joinZigzag64);
  513. };
  514. /**
  515. * Reads a signed, zigzag-encoded 64-bit varint from the binary stream
  516. * losslessly and returns it as an 8-character Unicode string for use as a hash
  517. * table key.
  518. *
  519. * Zigzag encoding is a modification of varint encoding that reduces the
  520. * storage overhead for small negative integers - for more details on the
  521. * format, see https://developers.google.com/protocol-buffers/docs/encoding
  522. *
  523. * @return {string} The decoded zigzag varint in hash64 format.
  524. */
  525. jspb.BinaryDecoder.prototype.readZigzagVarintHash64 = function() {
  526. return this.readSplitZigzagVarint64(jspb.utils.joinHash64);
  527. };
  528. /**
  529. * Reads a signed, zigzag-encoded 64-bit varint from the binary stream and
  530. * returns its value as a string.
  531. *
  532. * Zigzag encoding is a modification of varint encoding that reduces the
  533. * storage overhead for small negative integers - for more details on the
  534. * format, see https://developers.google.com/protocol-buffers/docs/encoding
  535. *
  536. * @return {string} The decoded signed, zigzag-encoded 64-bit varint as a
  537. * string.
  538. */
  539. jspb.BinaryDecoder.prototype.readZigzagVarint64String = function() {
  540. return this.readSplitZigzagVarint64(jspb.utils.joinSignedDecimalString);
  541. };
  542. /**
  543. * Reads a raw unsigned 8-bit integer from the binary stream.
  544. *
  545. * @return {number} The unsigned 8-bit integer read from the binary stream.
  546. */
  547. jspb.BinaryDecoder.prototype.readUint8 = function() {
  548. var a = this.bytes_[this.cursor_ + 0];
  549. this.cursor_ += 1;
  550. goog.asserts.assert(this.cursor_ <= this.end_);
  551. return a;
  552. };
  553. /**
  554. * Reads a raw unsigned 16-bit integer from the binary stream.
  555. *
  556. * @return {number} The unsigned 16-bit integer read from the binary stream.
  557. */
  558. jspb.BinaryDecoder.prototype.readUint16 = function() {
  559. var a = this.bytes_[this.cursor_ + 0];
  560. var b = this.bytes_[this.cursor_ + 1];
  561. this.cursor_ += 2;
  562. goog.asserts.assert(this.cursor_ <= this.end_);
  563. return (a << 0) | (b << 8);
  564. };
  565. /**
  566. * Reads a raw unsigned 32-bit integer from the binary stream.
  567. *
  568. * @return {number} The unsigned 32-bit integer read from the binary stream.
  569. */
  570. jspb.BinaryDecoder.prototype.readUint32 = function() {
  571. var a = this.bytes_[this.cursor_ + 0];
  572. var b = this.bytes_[this.cursor_ + 1];
  573. var c = this.bytes_[this.cursor_ + 2];
  574. var d = this.bytes_[this.cursor_ + 3];
  575. this.cursor_ += 4;
  576. goog.asserts.assert(this.cursor_ <= this.end_);
  577. return ((a << 0) | (b << 8) | (c << 16) | (d << 24)) >>> 0;
  578. };
  579. /**
  580. * Reads a raw unsigned 64-bit integer from the binary stream. Note that since
  581. * Javascript represents all numbers as double-precision floats, there will be
  582. * precision lost if the absolute value of the integer is larger than 2^53.
  583. *
  584. * @return {number} The unsigned 64-bit integer read from the binary stream.
  585. * Precision will be lost if the integer exceeds 2^53.
  586. */
  587. jspb.BinaryDecoder.prototype.readUint64 = function() {
  588. var bitsLow = this.readUint32();
  589. var bitsHigh = this.readUint32();
  590. return jspb.utils.joinUint64(bitsLow, bitsHigh);
  591. };
  592. /**
  593. * Reads a raw unsigned 64-bit integer from the binary stream. Note that since
  594. * Javascript represents all numbers as double-precision floats, there will be
  595. * precision lost if the absolute value of the integer is larger than 2^53.
  596. *
  597. * @return {string} The unsigned 64-bit integer read from the binary stream.
  598. */
  599. jspb.BinaryDecoder.prototype.readUint64String = function() {
  600. var bitsLow = this.readUint32();
  601. var bitsHigh = this.readUint32();
  602. return jspb.utils.joinUnsignedDecimalString(bitsLow, bitsHigh);
  603. };
  604. /**
  605. * Reads a raw signed 8-bit integer from the binary stream.
  606. *
  607. * @return {number} The signed 8-bit integer read from the binary stream.
  608. */
  609. jspb.BinaryDecoder.prototype.readInt8 = function() {
  610. var a = this.bytes_[this.cursor_ + 0];
  611. this.cursor_ += 1;
  612. goog.asserts.assert(this.cursor_ <= this.end_);
  613. return (a << 24) >> 24;
  614. };
  615. /**
  616. * Reads a raw signed 16-bit integer from the binary stream.
  617. *
  618. * @return {number} The signed 16-bit integer read from the binary stream.
  619. */
  620. jspb.BinaryDecoder.prototype.readInt16 = function() {
  621. var a = this.bytes_[this.cursor_ + 0];
  622. var b = this.bytes_[this.cursor_ + 1];
  623. this.cursor_ += 2;
  624. goog.asserts.assert(this.cursor_ <= this.end_);
  625. return (((a << 0) | (b << 8)) << 16) >> 16;
  626. };
  627. /**
  628. * Reads a raw signed 32-bit integer from the binary stream.
  629. *
  630. * @return {number} The signed 32-bit integer read from the binary stream.
  631. */
  632. jspb.BinaryDecoder.prototype.readInt32 = function() {
  633. var a = this.bytes_[this.cursor_ + 0];
  634. var b = this.bytes_[this.cursor_ + 1];
  635. var c = this.bytes_[this.cursor_ + 2];
  636. var d = this.bytes_[this.cursor_ + 3];
  637. this.cursor_ += 4;
  638. goog.asserts.assert(this.cursor_ <= this.end_);
  639. return (a << 0) | (b << 8) | (c << 16) | (d << 24);
  640. };
  641. /**
  642. * Reads a raw signed 64-bit integer from the binary stream. Note that since
  643. * Javascript represents all numbers as double-precision floats, there will be
  644. * precision lost if the absolute vlaue of the integer is larger than 2^53.
  645. *
  646. * @return {number} The signed 64-bit integer read from the binary stream.
  647. * Precision will be lost if the integer exceeds 2^53.
  648. */
  649. jspb.BinaryDecoder.prototype.readInt64 = function() {
  650. var bitsLow = this.readUint32();
  651. var bitsHigh = this.readUint32();
  652. return jspb.utils.joinInt64(bitsLow, bitsHigh);
  653. };
  654. /**
  655. * Reads a raw signed 64-bit integer from the binary stream and returns it as a
  656. * string.
  657. *
  658. * @return {string} The signed 64-bit integer read from the binary stream.
  659. * Precision will be lost if the integer exceeds 2^53.
  660. */
  661. jspb.BinaryDecoder.prototype.readInt64String = function() {
  662. var bitsLow = this.readUint32();
  663. var bitsHigh = this.readUint32();
  664. return jspb.utils.joinSignedDecimalString(bitsLow, bitsHigh);
  665. };
  666. /**
  667. * Reads a 32-bit floating-point number from the binary stream, using the
  668. * temporary buffer to realign the data.
  669. *
  670. * @return {number} The float read from the binary stream.
  671. */
  672. jspb.BinaryDecoder.prototype.readFloat = function() {
  673. var bitsLow = this.readUint32();
  674. var bitsHigh = 0;
  675. return jspb.utils.joinFloat32(bitsLow, bitsHigh);
  676. };
  677. /**
  678. * Reads a 64-bit floating-point number from the binary stream, using the
  679. * temporary buffer to realign the data.
  680. *
  681. * @return {number} The double read from the binary stream.
  682. */
  683. jspb.BinaryDecoder.prototype.readDouble = function() {
  684. var bitsLow = this.readUint32();
  685. var bitsHigh = this.readUint32();
  686. return jspb.utils.joinFloat64(bitsLow, bitsHigh);
  687. };
  688. /**
  689. * Reads a boolean value from the binary stream.
  690. * @return {boolean} The boolean read from the binary stream.
  691. */
  692. jspb.BinaryDecoder.prototype.readBool = function() {
  693. return !!this.bytes_[this.cursor_++];
  694. };
  695. /**
  696. * Reads an enum value from the binary stream, which are always encoded as
  697. * signed varints.
  698. * @return {number} The enum value read from the binary stream.
  699. */
  700. jspb.BinaryDecoder.prototype.readEnum = function() {
  701. return this.readSignedVarint32();
  702. };
  703. /**
  704. * Reads and parses a UTF-8 encoded unicode string from the stream.
  705. * The code is inspired by maps.vectortown.parse.StreamedDataViewReader.
  706. * Supports codepoints from U+0000 up to U+10FFFF.
  707. * (http://en.wikipedia.org/wiki/UTF-8).
  708. * @param {number} length The length of the string to read.
  709. * @return {string} The decoded string.
  710. */
  711. jspb.BinaryDecoder.prototype.readString = function(length) {
  712. var bytes = this.bytes_;
  713. var cursor = this.cursor_;
  714. var end = cursor + length;
  715. var codeUnits = [];
  716. var result = '';
  717. while (cursor < end) {
  718. var c = bytes[cursor++];
  719. if (c < 128) { // Regular 7-bit ASCII.
  720. codeUnits.push(c);
  721. } else if (c < 192) {
  722. // UTF-8 continuation mark. We are out of sync. This
  723. // might happen if we attempted to read a character
  724. // with more than four bytes.
  725. continue;
  726. } else if (c < 224) { // UTF-8 with two bytes.
  727. var c2 = bytes[cursor++];
  728. codeUnits.push(((c & 31) << 6) | (c2 & 63));
  729. } else if (c < 240) { // UTF-8 with three bytes.
  730. var c2 = bytes[cursor++];
  731. var c3 = bytes[cursor++];
  732. codeUnits.push(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
  733. } else if (c < 248) { // UTF-8 with 4 bytes.
  734. var c2 = bytes[cursor++];
  735. var c3 = bytes[cursor++];
  736. var c4 = bytes[cursor++];
  737. // Characters written on 4 bytes have 21 bits for a codepoint.
  738. // We can't fit that on 16bit characters, so we use surrogates.
  739. var codepoint = ((c & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63);
  740. // Surrogates formula from wikipedia.
  741. // 1. Subtract 0x10000 from codepoint
  742. codepoint -= 0x10000;
  743. // 2. Split this into the high 10-bit value and the low 10-bit value
  744. // 3. Add 0xD800 to the high value to form the high surrogate
  745. // 4. Add 0xDC00 to the low value to form the low surrogate:
  746. var low = (codepoint & 1023) + 0xDC00;
  747. var high = ((codepoint >> 10) & 1023) + 0xD800;
  748. codeUnits.push(high, low);
  749. }
  750. // Avoid exceeding the maximum stack size when calling `apply`.
  751. if (codeUnits.length >= 8192) {
  752. result += String.fromCharCode.apply(null, codeUnits);
  753. codeUnits.length = 0;
  754. }
  755. }
  756. result += goog.crypt.byteArrayToString(codeUnits);
  757. this.cursor_ = cursor;
  758. return result;
  759. };
  760. /**
  761. * Reads and parses a UTF-8 encoded unicode string (with length prefix) from
  762. * the stream.
  763. * @return {string} The decoded string.
  764. */
  765. jspb.BinaryDecoder.prototype.readStringWithLength = function() {
  766. var length = this.readUnsignedVarint32();
  767. return this.readString(length);
  768. };
  769. /**
  770. * Reads a block of raw bytes from the binary stream.
  771. *
  772. * @param {number} length The number of bytes to read.
  773. * @return {!Uint8Array} The decoded block of bytes, or an empty block if the
  774. * length was invalid.
  775. */
  776. jspb.BinaryDecoder.prototype.readBytes = function(length) {
  777. if (length < 0 ||
  778. this.cursor_ + length > this.bytes_.length) {
  779. this.error_ = true;
  780. goog.asserts.fail('Invalid byte length!');
  781. return new Uint8Array(0);
  782. }
  783. var result = this.bytes_.subarray(this.cursor_, this.cursor_ + length);
  784. this.cursor_ += length;
  785. goog.asserts.assert(this.cursor_ <= this.end_);
  786. return result;
  787. };
  788. /**
  789. * Reads a 64-bit varint from the stream and returns it as an 8-character
  790. * Unicode string for use as a hash table key.
  791. *
  792. * @return {string} The hash value.
  793. */
  794. jspb.BinaryDecoder.prototype.readVarintHash64 = function() {
  795. return this.readSplitVarint64(jspb.utils.joinHash64);
  796. };
  797. /**
  798. * Reads a 64-bit fixed-width value from the stream and returns it as an
  799. * 8-character Unicode string for use as a hash table key.
  800. *
  801. * @return {string} The hash value.
  802. */
  803. jspb.BinaryDecoder.prototype.readFixedHash64 = function() {
  804. var bytes = this.bytes_;
  805. var cursor = this.cursor_;
  806. var a = bytes[cursor + 0];
  807. var b = bytes[cursor + 1];
  808. var c = bytes[cursor + 2];
  809. var d = bytes[cursor + 3];
  810. var e = bytes[cursor + 4];
  811. var f = bytes[cursor + 5];
  812. var g = bytes[cursor + 6];
  813. var h = bytes[cursor + 7];
  814. this.cursor_ += 8;
  815. return String.fromCharCode(a, b, c, d, e, f, g, h);
  816. };