encoder.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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. // TODO(haberman): write lossless 64-bit zig-zag math.
  202. this.writeZigzagVarint64(parseInt(value, 10));
  203. };
  204. /**
  205. * Writes a 8-bit unsigned integer to the buffer. Numbers outside the range
  206. * [0,2^8) will be truncated.
  207. * @param {number} value The value to write.
  208. */
  209. jspb.BinaryEncoder.prototype.writeUint8 = function(value) {
  210. goog.asserts.assert(value == Math.floor(value));
  211. goog.asserts.assert((value >= 0) && (value < 256));
  212. this.buffer_.push((value >>> 0) & 0xFF);
  213. };
  214. /**
  215. * Writes a 16-bit unsigned integer to the buffer. Numbers outside the
  216. * range [0,2^16) will be truncated.
  217. * @param {number} value The value to write.
  218. */
  219. jspb.BinaryEncoder.prototype.writeUint16 = function(value) {
  220. goog.asserts.assert(value == Math.floor(value));
  221. goog.asserts.assert((value >= 0) && (value < 65536));
  222. this.buffer_.push((value >>> 0) & 0xFF);
  223. this.buffer_.push((value >>> 8) & 0xFF);
  224. };
  225. /**
  226. * Writes a 32-bit unsigned integer to the buffer. Numbers outside the
  227. * range [0,2^32) will be truncated.
  228. * @param {number} value The value to write.
  229. */
  230. jspb.BinaryEncoder.prototype.writeUint32 = function(value) {
  231. goog.asserts.assert(value == Math.floor(value));
  232. goog.asserts.assert((value >= 0) &&
  233. (value < jspb.BinaryConstants.TWO_TO_32));
  234. this.buffer_.push((value >>> 0) & 0xFF);
  235. this.buffer_.push((value >>> 8) & 0xFF);
  236. this.buffer_.push((value >>> 16) & 0xFF);
  237. this.buffer_.push((value >>> 24) & 0xFF);
  238. };
  239. /**
  240. * Writes a 64-bit unsigned integer to the buffer. Numbers outside the
  241. * range [0,2^64) will be truncated.
  242. * @param {number} value The value to write.
  243. */
  244. jspb.BinaryEncoder.prototype.writeUint64 = function(value) {
  245. goog.asserts.assert(value == Math.floor(value));
  246. goog.asserts.assert((value >= 0) &&
  247. (value < jspb.BinaryConstants.TWO_TO_64));
  248. jspb.utils.splitUint64(value);
  249. this.writeUint32(jspb.utils.split64Low);
  250. this.writeUint32(jspb.utils.split64High);
  251. };
  252. /**
  253. * Writes a 8-bit integer to the buffer. Numbers outside the range
  254. * [-2^7,2^7) will be truncated.
  255. * @param {number} value The value to write.
  256. */
  257. jspb.BinaryEncoder.prototype.writeInt8 = function(value) {
  258. goog.asserts.assert(value == Math.floor(value));
  259. goog.asserts.assert((value >= -128) && (value < 128));
  260. this.buffer_.push((value >>> 0) & 0xFF);
  261. };
  262. /**
  263. * Writes a 16-bit integer to the buffer. Numbers outside the range
  264. * [-2^15,2^15) will be truncated.
  265. * @param {number} value The value to write.
  266. */
  267. jspb.BinaryEncoder.prototype.writeInt16 = function(value) {
  268. goog.asserts.assert(value == Math.floor(value));
  269. goog.asserts.assert((value >= -32768) && (value < 32768));
  270. this.buffer_.push((value >>> 0) & 0xFF);
  271. this.buffer_.push((value >>> 8) & 0xFF);
  272. };
  273. /**
  274. * Writes a 32-bit integer to the buffer. Numbers outside the range
  275. * [-2^31,2^31) will be truncated.
  276. * @param {number} value The value to write.
  277. */
  278. jspb.BinaryEncoder.prototype.writeInt32 = function(value) {
  279. goog.asserts.assert(value == Math.floor(value));
  280. goog.asserts.assert((value >= -jspb.BinaryConstants.TWO_TO_31) &&
  281. (value < jspb.BinaryConstants.TWO_TO_31));
  282. this.buffer_.push((value >>> 0) & 0xFF);
  283. this.buffer_.push((value >>> 8) & 0xFF);
  284. this.buffer_.push((value >>> 16) & 0xFF);
  285. this.buffer_.push((value >>> 24) & 0xFF);
  286. };
  287. /**
  288. * Writes a 64-bit integer to the buffer. Numbers outside the range
  289. * [-2^63,2^63) will be truncated.
  290. * @param {number} value The value to write.
  291. */
  292. jspb.BinaryEncoder.prototype.writeInt64 = function(value) {
  293. goog.asserts.assert(value == Math.floor(value));
  294. goog.asserts.assert((value >= -jspb.BinaryConstants.TWO_TO_63) &&
  295. (value < jspb.BinaryConstants.TWO_TO_63));
  296. jspb.utils.splitInt64(value);
  297. this.writeSplitFixed64(jspb.utils.split64Low, jspb.utils.split64High);
  298. };
  299. /**
  300. * Writes a 64-bit integer decimal strings to the buffer. Numbers outside the
  301. * range [-2^63,2^63) will be truncated.
  302. * @param {string} value The value to write.
  303. */
  304. jspb.BinaryEncoder.prototype.writeInt64String = 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.splitHash64(jspb.utils.decimalStringToHash64(value));
  309. this.writeSplitFixed64(jspb.utils.split64Low, jspb.utils.split64High);
  310. };
  311. /**
  312. * Writes a single-precision floating point value to the buffer. Numbers
  313. * requiring more than 32 bits of precision will be truncated.
  314. * @param {number} value The value to write.
  315. */
  316. jspb.BinaryEncoder.prototype.writeFloat = function(value) {
  317. goog.asserts.assert((value >= -jspb.BinaryConstants.FLOAT32_MAX) &&
  318. (value <= jspb.BinaryConstants.FLOAT32_MAX));
  319. jspb.utils.splitFloat32(value);
  320. this.writeUint32(jspb.utils.split64Low);
  321. };
  322. /**
  323. * Writes a double-precision floating point value to the buffer. As this is
  324. * the native format used by JavaScript, no precision will be lost.
  325. * @param {number} value The value to write.
  326. */
  327. jspb.BinaryEncoder.prototype.writeDouble = function(value) {
  328. goog.asserts.assert((value >= -jspb.BinaryConstants.FLOAT64_MAX) &&
  329. (value <= jspb.BinaryConstants.FLOAT64_MAX));
  330. jspb.utils.splitFloat64(value);
  331. this.writeUint32(jspb.utils.split64Low);
  332. this.writeUint32(jspb.utils.split64High);
  333. };
  334. /**
  335. * Writes a boolean value to the buffer as a varint. We allow numbers as input
  336. * because the JSPB code generator uses 0/1 instead of true/false to save space
  337. * in the string representation of the proto.
  338. * @param {boolean|number} value The value to write.
  339. */
  340. jspb.BinaryEncoder.prototype.writeBool = function(value) {
  341. goog.asserts.assert(goog.isBoolean(value) || goog.isNumber(value));
  342. this.buffer_.push(value ? 1 : 0);
  343. };
  344. /**
  345. * Writes an enum value to the buffer as a varint.
  346. * @param {number} value The value to write.
  347. */
  348. jspb.BinaryEncoder.prototype.writeEnum = function(value) {
  349. goog.asserts.assert(value == Math.floor(value));
  350. goog.asserts.assert((value >= -jspb.BinaryConstants.TWO_TO_31) &&
  351. (value < jspb.BinaryConstants.TWO_TO_31));
  352. this.writeSignedVarint32(value);
  353. };
  354. /**
  355. * Writes an arbitrary byte array to the buffer.
  356. * @param {!Uint8Array} bytes The array of bytes to write.
  357. */
  358. jspb.BinaryEncoder.prototype.writeBytes = function(bytes) {
  359. this.buffer_.push.apply(this.buffer_, bytes);
  360. };
  361. /**
  362. * Writes a 64-bit hash string (8 characters @ 8 bits of data each) to the
  363. * buffer as a varint.
  364. * @param {string} hash The hash to write.
  365. */
  366. jspb.BinaryEncoder.prototype.writeVarintHash64 = function(hash) {
  367. jspb.utils.splitHash64(hash);
  368. this.writeSplitVarint64(jspb.utils.split64Low,
  369. jspb.utils.split64High);
  370. };
  371. /**
  372. * Writes a 64-bit hash string (8 characters @ 8 bits of data each) to the
  373. * buffer as a fixed64.
  374. * @param {string} hash The hash to write.
  375. */
  376. jspb.BinaryEncoder.prototype.writeFixedHash64 = function(hash) {
  377. jspb.utils.splitHash64(hash);
  378. this.writeUint32(jspb.utils.split64Low);
  379. this.writeUint32(jspb.utils.split64High);
  380. };
  381. /**
  382. * Writes a UTF16 Javascript string to the buffer encoded as UTF8.
  383. * TODO(aappleby): Add support for surrogate pairs, reject unpaired surrogates.
  384. * @param {string} value The string to write.
  385. * @return {number} The number of bytes used to encode the string.
  386. */
  387. jspb.BinaryEncoder.prototype.writeString = function(value) {
  388. var oldLength = this.buffer_.length;
  389. for (var i = 0; i < value.length; i++) {
  390. var c = value.charCodeAt(i);
  391. if (c < 128) {
  392. this.buffer_.push(c);
  393. } else if (c < 2048) {
  394. this.buffer_.push((c >> 6) | 192);
  395. this.buffer_.push((c & 63) | 128);
  396. } else if (c < 65536) {
  397. // Look for surrogates
  398. if (c >= 0xD800 && c <= 0xDBFF && i + 1 < value.length) {
  399. var second = value.charCodeAt(i + 1);
  400. if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
  401. // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
  402. c = (c - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
  403. this.buffer_.push((c >> 18) | 240);
  404. this.buffer_.push(((c >> 12) & 63 ) | 128);
  405. this.buffer_.push(((c >> 6) & 63) | 128);
  406. this.buffer_.push((c & 63) | 128);
  407. i++;
  408. }
  409. }
  410. else {
  411. this.buffer_.push((c >> 12) | 224);
  412. this.buffer_.push(((c >> 6) & 63) | 128);
  413. this.buffer_.push((c & 63) | 128);
  414. }
  415. }
  416. }
  417. var length = this.buffer_.length - oldLength;
  418. return length;
  419. };