encoder.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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 BinaryEncode defines methods for encoding Javascript values
  32. * into arrays of bytes compatible with the Protocol Buffer wire format.
  33. *
  34. * @author aappleby@google.com (Austin Appleby)
  35. */
  36. goog.provide('jspb.BinaryEncoder');
  37. goog.require('goog.asserts');
  38. goog.require('jspb.BinaryConstants');
  39. goog.require('jspb.utils');
  40. /**
  41. * BinaryEncoder implements encoders for all the wire types specified in
  42. * https://developers.google.com/protocol-buffers/docs/encoding.
  43. *
  44. * @constructor
  45. * @struct
  46. */
  47. jspb.BinaryEncoder = function() {
  48. /** @private {!Array<number>} */
  49. this.buffer_ = [];
  50. };
  51. /**
  52. * @return {number}
  53. */
  54. jspb.BinaryEncoder.prototype.length = function() {
  55. return this.buffer_.length;
  56. };
  57. /**
  58. * @return {!Array<number>}
  59. */
  60. jspb.BinaryEncoder.prototype.end = function() {
  61. var buffer = this.buffer_;
  62. this.buffer_ = [];
  63. return buffer;
  64. };
  65. /**
  66. * Encodes a 64-bit integer in 32:32 split representation into its wire-format
  67. * varint representation and stores it in the buffer.
  68. * @param {number} lowBits The low 32 bits of the int.
  69. * @param {number} highBits The high 32 bits of the int.
  70. */
  71. jspb.BinaryEncoder.prototype.writeSplitVarint64 = function(lowBits, highBits) {
  72. goog.asserts.assert(lowBits == Math.floor(lowBits));
  73. goog.asserts.assert(highBits == Math.floor(highBits));
  74. goog.asserts.assert((lowBits >= 0) &&
  75. (lowBits < jspb.BinaryConstants.TWO_TO_32));
  76. goog.asserts.assert((highBits >= 0) &&
  77. (highBits < jspb.BinaryConstants.TWO_TO_32));
  78. // Break the binary representation into chunks of 7 bits, set the 8th bit
  79. // in each chunk if it's not the final chunk, and append to the result.
  80. while (highBits > 0 || lowBits > 127) {
  81. this.buffer_.push((lowBits & 0x7f) | 0x80);
  82. lowBits = ((lowBits >>> 7) | (highBits << 25)) >>> 0;
  83. highBits = highBits >>> 7;
  84. }
  85. this.buffer_.push(lowBits);
  86. };
  87. /**
  88. * Encodes a 64-bit integer in 32:32 split representation into its wire-format
  89. * fixed representation and stores it in the buffer.
  90. * @param {number} lowBits The low 32 bits of the int.
  91. * @param {number} highBits The high 32 bits of the int.
  92. */
  93. jspb.BinaryEncoder.prototype.writeSplitFixed64 = function(lowBits, highBits) {
  94. goog.asserts.assert(lowBits == Math.floor(lowBits));
  95. goog.asserts.assert(highBits == Math.floor(highBits));
  96. goog.asserts.assert((lowBits >= 0) &&
  97. (lowBits < jspb.BinaryConstants.TWO_TO_32));
  98. goog.asserts.assert((highBits >= 0) &&
  99. (highBits < jspb.BinaryConstants.TWO_TO_32));
  100. this.writeUint32(lowBits);
  101. this.writeUint32(highBits);
  102. };
  103. /**
  104. * Encodes a 32-bit unsigned integer into its wire-format varint representation
  105. * and stores it in the buffer.
  106. * @param {number} value The integer to convert.
  107. */
  108. jspb.BinaryEncoder.prototype.writeUnsignedVarint32 = function(value) {
  109. goog.asserts.assert(value == Math.floor(value));
  110. goog.asserts.assert((value >= 0) &&
  111. (value < jspb.BinaryConstants.TWO_TO_32));
  112. while (value > 127) {
  113. this.buffer_.push((value & 0x7f) | 0x80);
  114. value = value >>> 7;
  115. }
  116. this.buffer_.push(value);
  117. };
  118. /**
  119. * Encodes a 32-bit signed integer into its wire-format varint representation
  120. * and stores it in the buffer.
  121. * @param {number} value The integer to convert.
  122. */
  123. jspb.BinaryEncoder.prototype.writeSignedVarint32 = function(value) {
  124. goog.asserts.assert(value == Math.floor(value));
  125. goog.asserts.assert((value >= -jspb.BinaryConstants.TWO_TO_31) &&
  126. (value < jspb.BinaryConstants.TWO_TO_31));
  127. // Use the unsigned version if the value is not negative.
  128. if (value >= 0) {
  129. this.writeUnsignedVarint32(value);
  130. return;
  131. }
  132. // Write nine bytes with a _signed_ right shift so we preserve the sign bit.
  133. for (var i = 0; i < 9; i++) {
  134. this.buffer_.push((value & 0x7f) | 0x80);
  135. value = value >> 7;
  136. }
  137. // The above loop writes out 63 bits, so the last byte is always the sign bit
  138. // which is always set for negative numbers.
  139. this.buffer_.push(1);
  140. };
  141. /**
  142. * Encodes a 64-bit unsigned integer into its wire-format varint representation
  143. * and stores it in the buffer. Integers that are not representable in 64 bits
  144. * will be truncated.
  145. * @param {number} value The integer to convert.
  146. */
  147. jspb.BinaryEncoder.prototype.writeUnsignedVarint64 = function(value) {
  148. goog.asserts.assert(value == Math.floor(value));
  149. goog.asserts.assert((value >= 0) &&
  150. (value < jspb.BinaryConstants.TWO_TO_64));
  151. jspb.utils.splitInt64(value);
  152. this.writeSplitVarint64(jspb.utils.split64Low,
  153. jspb.utils.split64High);
  154. };
  155. /**
  156. * Encodes a 64-bit signed integer into its wire-format varint representation
  157. * and stores it in the buffer. Integers that are not representable in 64 bits
  158. * will be truncated.
  159. * @param {number} value The integer to convert.
  160. */
  161. jspb.BinaryEncoder.prototype.writeSignedVarint64 = function(value) {
  162. goog.asserts.assert(value == Math.floor(value));
  163. goog.asserts.assert((value >= -jspb.BinaryConstants.TWO_TO_63) &&
  164. (value < jspb.BinaryConstants.TWO_TO_63));
  165. jspb.utils.splitInt64(value);
  166. this.writeSplitVarint64(jspb.utils.split64Low,
  167. jspb.utils.split64High);
  168. };
  169. /**
  170. * Encodes a JavaScript integer into its wire-format, zigzag-encoded varint
  171. * representation and stores it in the buffer.
  172. * @param {number} value The integer to convert.
  173. */
  174. jspb.BinaryEncoder.prototype.writeZigzagVarint32 = function(value) {
  175. goog.asserts.assert(value == Math.floor(value));
  176. goog.asserts.assert((value >= -jspb.BinaryConstants.TWO_TO_31) &&
  177. (value < jspb.BinaryConstants.TWO_TO_31));
  178. this.writeUnsignedVarint32(((value << 1) ^ (value >> 31)) >>> 0);
  179. };
  180. /**
  181. * Encodes a JavaScript integer into its wire-format, zigzag-encoded varint
  182. * representation and stores it in the buffer. Integers not representable in 64
  183. * bits will be truncated.
  184. * @param {number} value The integer to convert.
  185. */
  186. jspb.BinaryEncoder.prototype.writeZigzagVarint64 = function(value) {
  187. goog.asserts.assert(value == Math.floor(value));
  188. goog.asserts.assert((value >= -jspb.BinaryConstants.TWO_TO_63) &&
  189. (value < jspb.BinaryConstants.TWO_TO_63));
  190. jspb.utils.splitZigzag64(value);
  191. this.writeSplitVarint64(jspb.utils.split64Low,
  192. jspb.utils.split64High);
  193. };
  194. /**
  195. * Encodes a JavaScript decimal string into its wire-format, zigzag-encoded
  196. * varint representation and stores it in the buffer. Integers not representable
  197. * in 64 bits will be truncated.
  198. * @param {string} value The integer to convert.
  199. */
  200. jspb.BinaryEncoder.prototype.writeZigzagVarint64String = function(value) {
  201. this.writeZigzagVarintHash64(jspb.utils.decimalStringToHash64(value));
  202. };
  203. /**
  204. * Writes a 64-bit hash string (8 characters @ 8 bits of data each) to the
  205. * buffer as a zigzag varint.
  206. * @param {string} hash The hash to write.
  207. */
  208. jspb.BinaryEncoder.prototype.writeZigzagVarintHash64 = function(hash) {
  209. var self = this;
  210. jspb.utils.splitHash64(hash);
  211. jspb.utils.toZigzag64(
  212. jspb.utils.split64Low, jspb.utils.split64High, function(lo, hi) {
  213. self.writeSplitVarint64(lo >>> 0, hi >>> 0);
  214. });
  215. };
  216. /**
  217. * Writes an 8-bit unsigned integer to the buffer. Numbers outside the range
  218. * [0,2^8) will be truncated.
  219. * @param {number} value The value to write.
  220. */
  221. jspb.BinaryEncoder.prototype.writeUint8 = function(value) {
  222. goog.asserts.assert(value == Math.floor(value));
  223. goog.asserts.assert((value >= 0) && (value < 256));
  224. this.buffer_.push((value >>> 0) & 0xFF);
  225. };
  226. /**
  227. * Writes a 16-bit unsigned integer to the buffer. Numbers outside the
  228. * range [0,2^16) will be truncated.
  229. * @param {number} value The value to write.
  230. */
  231. jspb.BinaryEncoder.prototype.writeUint16 = function(value) {
  232. goog.asserts.assert(value == Math.floor(value));
  233. goog.asserts.assert((value >= 0) && (value < 65536));
  234. this.buffer_.push((value >>> 0) & 0xFF);
  235. this.buffer_.push((value >>> 8) & 0xFF);
  236. };
  237. /**
  238. * Writes a 32-bit unsigned integer to the buffer. Numbers outside the
  239. * range [0,2^32) will be truncated.
  240. * @param {number} value The value to write.
  241. */
  242. jspb.BinaryEncoder.prototype.writeUint32 = function(value) {
  243. goog.asserts.assert(value == Math.floor(value));
  244. goog.asserts.assert((value >= 0) &&
  245. (value < jspb.BinaryConstants.TWO_TO_32));
  246. this.buffer_.push((value >>> 0) & 0xFF);
  247. this.buffer_.push((value >>> 8) & 0xFF);
  248. this.buffer_.push((value >>> 16) & 0xFF);
  249. this.buffer_.push((value >>> 24) & 0xFF);
  250. };
  251. /**
  252. * Writes a 64-bit unsigned integer to the buffer. Numbers outside the
  253. * range [0,2^64) will be truncated.
  254. * @param {number} value The value to write.
  255. */
  256. jspb.BinaryEncoder.prototype.writeUint64 = function(value) {
  257. goog.asserts.assert(value == Math.floor(value));
  258. goog.asserts.assert((value >= 0) &&
  259. (value < jspb.BinaryConstants.TWO_TO_64));
  260. jspb.utils.splitUint64(value);
  261. this.writeUint32(jspb.utils.split64Low);
  262. this.writeUint32(jspb.utils.split64High);
  263. };
  264. /**
  265. * Writes an 8-bit integer to the buffer. Numbers outside the range
  266. * [-2^7,2^7) will be truncated.
  267. * @param {number} value The value to write.
  268. */
  269. jspb.BinaryEncoder.prototype.writeInt8 = function(value) {
  270. goog.asserts.assert(value == Math.floor(value));
  271. goog.asserts.assert((value >= -128) && (value < 128));
  272. this.buffer_.push((value >>> 0) & 0xFF);
  273. };
  274. /**
  275. * Writes a 16-bit integer to the buffer. Numbers outside the range
  276. * [-2^15,2^15) will be truncated.
  277. * @param {number} value The value to write.
  278. */
  279. jspb.BinaryEncoder.prototype.writeInt16 = function(value) {
  280. goog.asserts.assert(value == Math.floor(value));
  281. goog.asserts.assert((value >= -32768) && (value < 32768));
  282. this.buffer_.push((value >>> 0) & 0xFF);
  283. this.buffer_.push((value >>> 8) & 0xFF);
  284. };
  285. /**
  286. * Writes a 32-bit integer to the buffer. Numbers outside the range
  287. * [-2^31,2^31) will be truncated.
  288. * @param {number} value The value to write.
  289. */
  290. jspb.BinaryEncoder.prototype.writeInt32 = function(value) {
  291. goog.asserts.assert(value == Math.floor(value));
  292. goog.asserts.assert((value >= -jspb.BinaryConstants.TWO_TO_31) &&
  293. (value < jspb.BinaryConstants.TWO_TO_31));
  294. this.buffer_.push((value >>> 0) & 0xFF);
  295. this.buffer_.push((value >>> 8) & 0xFF);
  296. this.buffer_.push((value >>> 16) & 0xFF);
  297. this.buffer_.push((value >>> 24) & 0xFF);
  298. };
  299. /**
  300. * Writes a 64-bit integer to the buffer. Numbers outside the range
  301. * [-2^63,2^63) will be truncated.
  302. * @param {number} value The value to write.
  303. */
  304. jspb.BinaryEncoder.prototype.writeInt64 = function(value) {
  305. goog.asserts.assert(value == Math.floor(value));
  306. goog.asserts.assert((value >= -jspb.BinaryConstants.TWO_TO_63) &&
  307. (value < jspb.BinaryConstants.TWO_TO_63));
  308. jspb.utils.splitInt64(value);
  309. this.writeSplitFixed64(jspb.utils.split64Low, jspb.utils.split64High);
  310. };
  311. /**
  312. * Writes a 64-bit integer decimal strings to the buffer. Numbers outside the
  313. * range [-2^63,2^63) will be truncated.
  314. * @param {string} value The value to write.
  315. */
  316. jspb.BinaryEncoder.prototype.writeInt64String = function(value) {
  317. goog.asserts.assert(value == Math.floor(value));
  318. goog.asserts.assert((+value >= -jspb.BinaryConstants.TWO_TO_63) &&
  319. (+value < jspb.BinaryConstants.TWO_TO_63));
  320. jspb.utils.splitHash64(jspb.utils.decimalStringToHash64(value));
  321. this.writeSplitFixed64(jspb.utils.split64Low, jspb.utils.split64High);
  322. };
  323. /**
  324. * Writes a single-precision floating point value to the buffer. Numbers
  325. * requiring more than 32 bits of precision will be truncated.
  326. * @param {number} value The value to write.
  327. */
  328. jspb.BinaryEncoder.prototype.writeFloat = function(value) {
  329. goog.asserts.assert(
  330. value === Infinity || value === -Infinity || isNaN(value) ||
  331. ((value >= -jspb.BinaryConstants.FLOAT32_MAX) &&
  332. (value <= jspb.BinaryConstants.FLOAT32_MAX)));
  333. jspb.utils.splitFloat32(value);
  334. this.writeUint32(jspb.utils.split64Low);
  335. };
  336. /**
  337. * Writes a double-precision floating point value to the buffer. As this is
  338. * the native format used by JavaScript, no precision will be lost.
  339. * @param {number} value The value to write.
  340. */
  341. jspb.BinaryEncoder.prototype.writeDouble = function(value) {
  342. goog.asserts.assert(
  343. value === Infinity || value === -Infinity || isNaN(value) ||
  344. ((value >= -jspb.BinaryConstants.FLOAT64_MAX) &&
  345. (value <= jspb.BinaryConstants.FLOAT64_MAX)));
  346. jspb.utils.splitFloat64(value);
  347. this.writeUint32(jspb.utils.split64Low);
  348. this.writeUint32(jspb.utils.split64High);
  349. };
  350. /**
  351. * Writes a boolean value to the buffer as a varint. We allow numbers as input
  352. * because the JSPB code generator uses 0/1 instead of true/false to save space
  353. * in the string representation of the proto.
  354. * @param {boolean|number} value The value to write.
  355. */
  356. jspb.BinaryEncoder.prototype.writeBool = function(value) {
  357. goog.asserts.assert(typeof value === 'boolean' || typeof value === 'number');
  358. this.buffer_.push(value ? 1 : 0);
  359. };
  360. /**
  361. * Writes an enum value to the buffer as a varint.
  362. * @param {number} value The value to write.
  363. */
  364. jspb.BinaryEncoder.prototype.writeEnum = function(value) {
  365. goog.asserts.assert(value == Math.floor(value));
  366. goog.asserts.assert((value >= -jspb.BinaryConstants.TWO_TO_31) &&
  367. (value < jspb.BinaryConstants.TWO_TO_31));
  368. this.writeSignedVarint32(value);
  369. };
  370. /**
  371. * Writes an arbitrary byte array to the buffer.
  372. * @param {!Uint8Array} bytes The array of bytes to write.
  373. */
  374. jspb.BinaryEncoder.prototype.writeBytes = function(bytes) {
  375. this.buffer_.push.apply(this.buffer_, bytes);
  376. };
  377. /**
  378. * Writes a 64-bit hash string (8 characters @ 8 bits of data each) to the
  379. * buffer as a varint.
  380. * @param {string} hash The hash to write.
  381. */
  382. jspb.BinaryEncoder.prototype.writeVarintHash64 = function(hash) {
  383. jspb.utils.splitHash64(hash);
  384. this.writeSplitVarint64(jspb.utils.split64Low,
  385. jspb.utils.split64High);
  386. };
  387. /**
  388. * Writes a 64-bit hash string (8 characters @ 8 bits of data each) to the
  389. * buffer as a fixed64.
  390. * @param {string} hash The hash to write.
  391. */
  392. jspb.BinaryEncoder.prototype.writeFixedHash64 = function(hash) {
  393. jspb.utils.splitHash64(hash);
  394. this.writeUint32(jspb.utils.split64Low);
  395. this.writeUint32(jspb.utils.split64High);
  396. };
  397. /**
  398. * Writes a UTF16 Javascript string to the buffer encoded as UTF8.
  399. * TODO(aappleby): Add support for surrogate pairs, reject unpaired surrogates.
  400. * @param {string} value The string to write.
  401. * @return {number} The number of bytes used to encode the string.
  402. */
  403. jspb.BinaryEncoder.prototype.writeString = function(value) {
  404. var oldLength = this.buffer_.length;
  405. for (var i = 0; i < value.length; i++) {
  406. var c = value.charCodeAt(i);
  407. if (c < 128) {
  408. this.buffer_.push(c);
  409. } else if (c < 2048) {
  410. this.buffer_.push((c >> 6) | 192);
  411. this.buffer_.push((c & 63) | 128);
  412. } else if (c < 65536) {
  413. // Look for surrogates
  414. if (c >= 0xD800 && c <= 0xDBFF && i + 1 < value.length) {
  415. var second = value.charCodeAt(i + 1);
  416. if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
  417. // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
  418. c = (c - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
  419. this.buffer_.push((c >> 18) | 240);
  420. this.buffer_.push(((c >> 12) & 63 ) | 128);
  421. this.buffer_.push(((c >> 6) & 63) | 128);
  422. this.buffer_.push((c & 63) | 128);
  423. i++;
  424. }
  425. }
  426. else {
  427. this.buffer_.push((c >> 12) | 224);
  428. this.buffer_.push(((c >> 6) & 63) | 128);
  429. this.buffer_.push((c & 63) | 128);
  430. }
  431. }
  432. }
  433. var length = this.buffer_.length - oldLength;
  434. return length;
  435. };