decoder.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
  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>} */
  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 ? 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. Those
  498. // bits _must_ be zero, or the encoding is invalid.
  499. goog.asserts.assert((temp & 0xF0) == 0);
  500. this.cursor_ += 5;
  501. goog.asserts.assert(this.cursor_ <= this.end_);
  502. return x >>> 0;
  503. }
  504. // If we get here, we're reading the sign extension of a negative 32-bit int.
  505. // We can skip these bytes, as we know in advance that they have to be all
  506. // 1's if the varint is correctly encoded. Since we also know the value is
  507. // negative, we don't have to coerce it to unsigned before we return it.
  508. goog.asserts.assert((temp & 0xF0) == 0xF0);
  509. goog.asserts.assert(bytes[this.cursor_ + 5] == 0xFF);
  510. goog.asserts.assert(bytes[this.cursor_ + 6] == 0xFF);
  511. goog.asserts.assert(bytes[this.cursor_ + 7] == 0xFF);
  512. goog.asserts.assert(bytes[this.cursor_ + 8] == 0xFF);
  513. goog.asserts.assert(bytes[this.cursor_ + 9] == 0x01);
  514. this.cursor_ += 10;
  515. goog.asserts.assert(this.cursor_ <= this.end_);
  516. return x;
  517. };
  518. /**
  519. * The readUnsignedVarint32 above deals with signed 32-bit varints correctly,
  520. * so this is just an alias.
  521. *
  522. * @return {number} The decoded signed 32-bit varint.
  523. */
  524. jspb.BinaryDecoder.prototype.readSignedVarint32 =
  525. jspb.BinaryDecoder.prototype.readUnsignedVarint32;
  526. /**
  527. * Reads a 32-bit unsigned variant and returns its value as a string.
  528. *
  529. * @return {string} The decoded unsigned 32-bit varint as a string.
  530. */
  531. jspb.BinaryDecoder.prototype.readUnsignedVarint32String = function() {
  532. // 32-bit integers fit in JavaScript numbers without loss of precision, so
  533. // string variants of 32-bit varint readers can simply delegate then convert
  534. // to string.
  535. var value = this.readUnsignedVarint32();
  536. return value.toString();
  537. };
  538. /**
  539. * Reads a 32-bit signed variant and returns its value as a string.
  540. *
  541. * @return {string} The decoded signed 32-bit varint as a string.
  542. */
  543. jspb.BinaryDecoder.prototype.readSignedVarint32String = function() {
  544. // 32-bit integers fit in JavaScript numbers without loss of precision, so
  545. // string variants of 32-bit varint readers can simply delegate then convert
  546. // to string.
  547. var value = this.readSignedVarint32();
  548. return value.toString();
  549. };
  550. /**
  551. * Reads a signed, zigzag-encoded 32-bit varint from the binary stream.
  552. *
  553. * Zigzag encoding is a modification of varint encoding that reduces the
  554. * storage overhead for small negative integers - for more details on the
  555. * format, see https://developers.google.com/protocol-buffers/docs/encoding
  556. *
  557. * @return {number} The decoded signed, zigzag-encoded 32-bit varint.
  558. */
  559. jspb.BinaryDecoder.prototype.readZigzagVarint32 = function() {
  560. var result = this.readUnsignedVarint32();
  561. return (result >>> 1) ^ - (result & 1);
  562. };
  563. /**
  564. * Reads an unsigned 64-bit varint from the binary stream. Note that since
  565. * Javascript represents all numbers as double-precision floats, there will be
  566. * precision lost if the absolute value of the varint is larger than 2^53.
  567. *
  568. * @return {number} The decoded unsigned varint. Precision will be lost if the
  569. * integer exceeds 2^53.
  570. */
  571. jspb.BinaryDecoder.prototype.readUnsignedVarint64 = function() {
  572. this.readSplitVarint64_();
  573. return jspb.utils.joinUint64(this.tempLow_, this.tempHigh_);
  574. };
  575. /**
  576. * Reads an unsigned 64-bit varint from the binary stream and returns the value
  577. * as a decimal string.
  578. *
  579. * @return {string} The decoded unsigned varint as a decimal string.
  580. */
  581. jspb.BinaryDecoder.prototype.readUnsignedVarint64String = function() {
  582. this.readSplitVarint64_();
  583. return jspb.utils.joinUnsignedDecimalString(this.tempLow_, this.tempHigh_);
  584. };
  585. /**
  586. * Reads a signed 64-bit varint from the binary stream. Note that since
  587. * Javascript represents all numbers as double-precision floats, there will be
  588. * precision lost if the absolute value of the varint is larger than 2^53.
  589. *
  590. * @return {number} The decoded signed varint. Precision will be lost if the
  591. * integer exceeds 2^53.
  592. */
  593. jspb.BinaryDecoder.prototype.readSignedVarint64 = function() {
  594. this.readSplitVarint64_();
  595. return jspb.utils.joinInt64(this.tempLow_, this.tempHigh_);
  596. };
  597. /**
  598. * Reads an signed 64-bit varint from the binary stream and returns the value
  599. * as a decimal string.
  600. *
  601. * @return {string} The decoded signed varint as a decimal string.
  602. */
  603. jspb.BinaryDecoder.prototype.readSignedVarint64String = function() {
  604. this.readSplitVarint64_();
  605. return jspb.utils.joinSignedDecimalString(this.tempLow_, this.tempHigh_);
  606. };
  607. /**
  608. * Reads a signed, zigzag-encoded 64-bit varint from the binary stream. Note
  609. * that since Javascript represents all numbers as double-precision floats,
  610. * there will be precision lost if the absolute value of the varint is larger
  611. * than 2^53.
  612. *
  613. * Zigzag encoding is a modification of varint encoding that reduces the
  614. * storage overhead for small negative integers - for more details on the
  615. * format, see https://developers.google.com/protocol-buffers/docs/encoding
  616. *
  617. * @return {number} The decoded zigzag varint. Precision will be lost if the
  618. * integer exceeds 2^53.
  619. */
  620. jspb.BinaryDecoder.prototype.readZigzagVarint64 = function() {
  621. this.readSplitVarint64_();
  622. return jspb.utils.joinZigzag64(this.tempLow_, this.tempHigh_);
  623. };
  624. /**
  625. * Reads a raw unsigned 8-bit integer from the binary stream.
  626. *
  627. * @return {number} The unsigned 8-bit integer read from the binary stream.
  628. */
  629. jspb.BinaryDecoder.prototype.readUint8 = function() {
  630. var a = this.bytes_[this.cursor_ + 0];
  631. this.cursor_ += 1;
  632. goog.asserts.assert(this.cursor_ <= this.end_);
  633. return a;
  634. };
  635. /**
  636. * Reads a raw unsigned 16-bit integer from the binary stream.
  637. *
  638. * @return {number} The unsigned 16-bit integer read from the binary stream.
  639. */
  640. jspb.BinaryDecoder.prototype.readUint16 = function() {
  641. var a = this.bytes_[this.cursor_ + 0];
  642. var b = this.bytes_[this.cursor_ + 1];
  643. this.cursor_ += 2;
  644. goog.asserts.assert(this.cursor_ <= this.end_);
  645. return (a << 0) | (b << 8);
  646. };
  647. /**
  648. * Reads a raw unsigned 32-bit integer from the binary stream.
  649. *
  650. * @return {number} The unsigned 32-bit integer read from the binary stream.
  651. */
  652. jspb.BinaryDecoder.prototype.readUint32 = function() {
  653. var a = this.bytes_[this.cursor_ + 0];
  654. var b = this.bytes_[this.cursor_ + 1];
  655. var c = this.bytes_[this.cursor_ + 2];
  656. var d = this.bytes_[this.cursor_ + 3];
  657. this.cursor_ += 4;
  658. goog.asserts.assert(this.cursor_ <= this.end_);
  659. return ((a << 0) | (b << 8) | (c << 16) | (d << 24)) >>> 0;
  660. };
  661. /**
  662. * Reads a raw unsigned 64-bit integer from the binary stream. Note that since
  663. * Javascript represents all numbers as double-precision floats, there will be
  664. * precision lost if the absolute value of the integer is larger than 2^53.
  665. *
  666. * @return {number} The unsigned 64-bit integer read from the binary stream.
  667. * Precision will be lost if the integer exceeds 2^53.
  668. */
  669. jspb.BinaryDecoder.prototype.readUint64 = function() {
  670. var bitsLow = this.readUint32();
  671. var bitsHigh = this.readUint32();
  672. return jspb.utils.joinUint64(bitsLow, bitsHigh);
  673. };
  674. /**
  675. * Reads a raw signed 8-bit integer from the binary stream.
  676. *
  677. * @return {number} The signed 8-bit integer read from the binary stream.
  678. */
  679. jspb.BinaryDecoder.prototype.readInt8 = function() {
  680. var a = this.bytes_[this.cursor_ + 0];
  681. this.cursor_ += 1;
  682. goog.asserts.assert(this.cursor_ <= this.end_);
  683. return (a << 24) >> 24;
  684. };
  685. /**
  686. * Reads a raw signed 16-bit integer from the binary stream.
  687. *
  688. * @return {number} The signed 16-bit integer read from the binary stream.
  689. */
  690. jspb.BinaryDecoder.prototype.readInt16 = function() {
  691. var a = this.bytes_[this.cursor_ + 0];
  692. var b = this.bytes_[this.cursor_ + 1];
  693. this.cursor_ += 2;
  694. goog.asserts.assert(this.cursor_ <= this.end_);
  695. return (((a << 0) | (b << 8)) << 16) >> 16;
  696. };
  697. /**
  698. * Reads a raw signed 32-bit integer from the binary stream.
  699. *
  700. * @return {number} The signed 32-bit integer read from the binary stream.
  701. */
  702. jspb.BinaryDecoder.prototype.readInt32 = function() {
  703. var a = this.bytes_[this.cursor_ + 0];
  704. var b = this.bytes_[this.cursor_ + 1];
  705. var c = this.bytes_[this.cursor_ + 2];
  706. var d = this.bytes_[this.cursor_ + 3];
  707. this.cursor_ += 4;
  708. goog.asserts.assert(this.cursor_ <= this.end_);
  709. return (a << 0) | (b << 8) | (c << 16) | (d << 24);
  710. };
  711. /**
  712. * Reads a raw signed 64-bit integer from the binary stream. Note that since
  713. * Javascript represents all numbers as double-precision floats, there will be
  714. * precision lost if the absolute vlaue of the integer is larger than 2^53.
  715. *
  716. * @return {number} The signed 64-bit integer read from the binary stream.
  717. * Precision will be lost if the integer exceeds 2^53.
  718. */
  719. jspb.BinaryDecoder.prototype.readInt64 = function() {
  720. var bitsLow = this.readUint32();
  721. var bitsHigh = this.readUint32();
  722. return jspb.utils.joinInt64(bitsLow, bitsHigh);
  723. };
  724. /**
  725. * Reads a 32-bit floating-point number from the binary stream, using the
  726. * temporary buffer to realign the data.
  727. *
  728. * @return {number} The float read from the binary stream.
  729. */
  730. jspb.BinaryDecoder.prototype.readFloat = function() {
  731. var bitsLow = this.readUint32();
  732. var bitsHigh = 0;
  733. return jspb.utils.joinFloat32(bitsLow, bitsHigh);
  734. };
  735. /**
  736. * Reads a 64-bit floating-point number from the binary stream, using the
  737. * temporary buffer to realign the data.
  738. *
  739. * @return {number} The double read from the binary stream.
  740. */
  741. jspb.BinaryDecoder.prototype.readDouble = function() {
  742. var bitsLow = this.readUint32();
  743. var bitsHigh = this.readUint32();
  744. return jspb.utils.joinFloat64(bitsLow, bitsHigh);
  745. };
  746. /**
  747. * Reads a boolean value from the binary stream.
  748. * @return {boolean} The boolean read from the binary stream.
  749. */
  750. jspb.BinaryDecoder.prototype.readBool = function() {
  751. return !!this.bytes_[this.cursor_++];
  752. };
  753. /**
  754. * Reads an enum value from the binary stream, which are always encoded as
  755. * signed varints.
  756. * @return {number} The enum value read from the binary stream.
  757. */
  758. jspb.BinaryDecoder.prototype.readEnum = function() {
  759. return this.readSignedVarint32();
  760. };
  761. /**
  762. * Reads and parses a UTF-8 encoded unicode string from the stream.
  763. * The code is inspired by maps.vectortown.parse.StreamedDataViewReader, with
  764. * the exception that the implementation here does not get confused if it
  765. * encounters characters longer than three bytes. These characters are ignored
  766. * though, as they are extremely rare: three UTF-8 bytes cover virtually all
  767. * characters in common use (http://en.wikipedia.org/wiki/UTF-8).
  768. * @param {number} length The length of the string to read.
  769. * @return {string} The decoded string.
  770. */
  771. jspb.BinaryDecoder.prototype.readString = function(length) {
  772. var bytes = this.bytes_;
  773. var cursor = this.cursor_;
  774. var end = cursor + length;
  775. var chars = [];
  776. while (cursor < end) {
  777. var c = bytes[cursor++];
  778. if (c < 128) { // Regular 7-bit ASCII.
  779. chars.push(c);
  780. } else if (c < 192) {
  781. // UTF-8 continuation mark. We are out of sync. This
  782. // might happen if we attempted to read a character
  783. // with more than three bytes.
  784. continue;
  785. } else if (c < 224) { // UTF-8 with two bytes.
  786. var c2 = bytes[cursor++];
  787. chars.push(((c & 31) << 6) | (c2 & 63));
  788. } else if (c < 240) { // UTF-8 with three bytes.
  789. var c2 = bytes[cursor++];
  790. var c3 = bytes[cursor++];
  791. chars.push(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
  792. }
  793. }
  794. // String.fromCharCode.apply is faster than manually appending characters on
  795. // Chrome 25+, and generates no additional cons string garbage.
  796. var result = String.fromCharCode.apply(null, chars);
  797. this.cursor_ = cursor;
  798. return result;
  799. };
  800. /**
  801. * Reads and parses a UTF-8 encoded unicode string (with length prefix) from
  802. * the stream.
  803. * @return {string} The decoded string.
  804. */
  805. jspb.BinaryDecoder.prototype.readStringWithLength = function() {
  806. var length = this.readUnsignedVarint32();
  807. return this.readString(length);
  808. };
  809. /**
  810. * Reads a block of raw bytes from the binary stream.
  811. *
  812. * @param {number} length The number of bytes to read.
  813. * @return {Uint8Array} The decoded block of bytes, or null if the length was
  814. * invalid.
  815. */
  816. jspb.BinaryDecoder.prototype.readBytes = function(length) {
  817. if (length < 0 ||
  818. this.cursor_ + length > this.bytes_.length) {
  819. this.error_ = true;
  820. return null;
  821. }
  822. var result = this.bytes_.subarray(this.cursor_, this.cursor_ + length);
  823. this.cursor_ += length;
  824. goog.asserts.assert(this.cursor_ <= this.end_);
  825. return result;
  826. };
  827. /**
  828. * Reads a 64-bit varint from the stream and returns it as an 8-character
  829. * Unicode string for use as a hash table key.
  830. *
  831. * @return {string} The hash value.
  832. */
  833. jspb.BinaryDecoder.prototype.readVarintHash64 = function() {
  834. this.readSplitVarint64_();
  835. return jspb.utils.joinHash64(this.tempLow_, this.tempHigh_);
  836. };
  837. /**
  838. * Reads a 64-bit fixed-width value from the stream and returns it as an
  839. * 8-character Unicode string for use as a hash table key.
  840. *
  841. * @return {string} The hash value.
  842. */
  843. jspb.BinaryDecoder.prototype.readFixedHash64 = function() {
  844. var bytes = this.bytes_;
  845. var cursor = this.cursor_;
  846. var a = bytes[cursor + 0];
  847. var b = bytes[cursor + 1];
  848. var c = bytes[cursor + 2];
  849. var d = bytes[cursor + 3];
  850. var e = bytes[cursor + 4];
  851. var f = bytes[cursor + 5];
  852. var g = bytes[cursor + 6];
  853. var h = bytes[cursor + 7];
  854. this.cursor_ += 8;
  855. return String.fromCharCode(a, b, c, d, e, f, g, h);
  856. };