decoder.js 31 KB

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