encoder.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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 32-bit unsigned integer into its wire-format varint representation
  89. * and stores it in the buffer.
  90. * @param {number} value The integer to convert.
  91. */
  92. jspb.BinaryEncoder.prototype.writeUnsignedVarint32 = function(value) {
  93. goog.asserts.assert(value == Math.floor(value));
  94. goog.asserts.assert((value >= 0) &&
  95. (value < jspb.BinaryConstants.TWO_TO_32));
  96. while (value > 127) {
  97. this.buffer_.push((value & 0x7f) | 0x80);
  98. value = value >>> 7;
  99. }
  100. this.buffer_.push(value);
  101. };
  102. /**
  103. * Encodes a 32-bit signed integer into its wire-format varint representation
  104. * and stores it in the buffer.
  105. * @param {number} value The integer to convert.
  106. */
  107. jspb.BinaryEncoder.prototype.writeSignedVarint32 = function(value) {
  108. goog.asserts.assert(value == Math.floor(value));
  109. goog.asserts.assert((value >= -jspb.BinaryConstants.TWO_TO_31) &&
  110. (value < jspb.BinaryConstants.TWO_TO_31));
  111. // Use the unsigned version if the value is not negative.
  112. if (value >= 0) {
  113. this.writeUnsignedVarint32(value);
  114. return;
  115. }
  116. // Write nine bytes with a _signed_ right shift so we preserve the sign bit.
  117. for (var i = 0; i < 9; i++) {
  118. this.buffer_.push((value & 0x7f) | 0x80);
  119. value = value >> 7;
  120. }
  121. // The above loop writes out 63 bits, so the last byte is always the sign bit
  122. // which is always set for negative numbers.
  123. this.buffer_.push(1);
  124. };
  125. /**
  126. * Encodes a 64-bit unsigned integer into its wire-format varint representation
  127. * and stores it in the buffer. Integers that are not representable in 64 bits
  128. * will be truncated.
  129. * @param {number} value The integer to convert.
  130. */
  131. jspb.BinaryEncoder.prototype.writeUnsignedVarint64 = function(value) {
  132. goog.asserts.assert(value == Math.floor(value));
  133. goog.asserts.assert((value >= 0) &&
  134. (value < jspb.BinaryConstants.TWO_TO_64));
  135. jspb.utils.splitInt64(value);
  136. this.writeSplitVarint64(jspb.utils.split64Low,
  137. jspb.utils.split64High);
  138. };
  139. /**
  140. * Encodes a 64-bit signed integer into its wire-format varint representation
  141. * and stores it in the buffer. Integers that are not representable in 64 bits
  142. * will be truncated.
  143. * @param {number} value The integer to convert.
  144. */
  145. jspb.BinaryEncoder.prototype.writeSignedVarint64 = function(value) {
  146. goog.asserts.assert(value == Math.floor(value));
  147. goog.asserts.assert((value >= -jspb.BinaryConstants.TWO_TO_63) &&
  148. (value < jspb.BinaryConstants.TWO_TO_63));
  149. jspb.utils.splitInt64(value);
  150. this.writeSplitVarint64(jspb.utils.split64Low,
  151. jspb.utils.split64High);
  152. };
  153. /**
  154. * Encodes a JavaScript integer into its wire-format, zigzag-encoded varint
  155. * representation and stores it in the buffer.
  156. * @param {number} value The integer to convert.
  157. */
  158. jspb.BinaryEncoder.prototype.writeZigzagVarint32 = function(value) {
  159. goog.asserts.assert(value == Math.floor(value));
  160. goog.asserts.assert((value >= -jspb.BinaryConstants.TWO_TO_31) &&
  161. (value < jspb.BinaryConstants.TWO_TO_31));
  162. this.writeUnsignedVarint32(((value << 1) ^ (value >> 31)) >>> 0);
  163. };
  164. /**
  165. * Encodes a JavaScript integer into its wire-format, zigzag-encoded varint
  166. * representation and stores it in the buffer. Integers not representable in 64
  167. * bits will be truncated.
  168. * @param {number} value The integer to convert.
  169. */
  170. jspb.BinaryEncoder.prototype.writeZigzagVarint64 = function(value) {
  171. goog.asserts.assert(value == Math.floor(value));
  172. goog.asserts.assert((value >= -jspb.BinaryConstants.TWO_TO_63) &&
  173. (value < jspb.BinaryConstants.TWO_TO_63));
  174. jspb.utils.splitZigzag64(value);
  175. this.writeSplitVarint64(jspb.utils.split64Low,
  176. jspb.utils.split64High);
  177. };
  178. /**
  179. * Writes a 8-bit unsigned integer to the buffer. Numbers outside the range
  180. * [0,2^8) will be truncated.
  181. * @param {number} value The value to write.
  182. */
  183. jspb.BinaryEncoder.prototype.writeUint8 = function(value) {
  184. goog.asserts.assert(value == Math.floor(value));
  185. goog.asserts.assert((value >= 0) && (value < 256));
  186. this.buffer_.push((value >>> 0) & 0xFF);
  187. };
  188. /**
  189. * Writes a 16-bit unsigned integer to the buffer. Numbers outside the
  190. * range [0,2^16) will be truncated.
  191. * @param {number} value The value to write.
  192. */
  193. jspb.BinaryEncoder.prototype.writeUint16 = function(value) {
  194. goog.asserts.assert(value == Math.floor(value));
  195. goog.asserts.assert((value >= 0) && (value < 65536));
  196. this.buffer_.push((value >>> 0) & 0xFF);
  197. this.buffer_.push((value >>> 8) & 0xFF);
  198. };
  199. /**
  200. * Writes a 32-bit unsigned integer to the buffer. Numbers outside the
  201. * range [0,2^32) will be truncated.
  202. * @param {number} value The value to write.
  203. */
  204. jspb.BinaryEncoder.prototype.writeUint32 = function(value) {
  205. goog.asserts.assert(value == Math.floor(value));
  206. goog.asserts.assert((value >= 0) &&
  207. (value < jspb.BinaryConstants.TWO_TO_32));
  208. this.buffer_.push((value >>> 0) & 0xFF);
  209. this.buffer_.push((value >>> 8) & 0xFF);
  210. this.buffer_.push((value >>> 16) & 0xFF);
  211. this.buffer_.push((value >>> 24) & 0xFF);
  212. };
  213. /**
  214. * Writes a 64-bit unsigned integer to the buffer. Numbers outside the
  215. * range [0,2^64) will be truncated.
  216. * @param {number} value The value to write.
  217. */
  218. jspb.BinaryEncoder.prototype.writeUint64 = function(value) {
  219. goog.asserts.assert(value == Math.floor(value));
  220. goog.asserts.assert((value >= 0) &&
  221. (value < jspb.BinaryConstants.TWO_TO_64));
  222. jspb.utils.splitUint64(value);
  223. this.writeUint32(jspb.utils.split64Low);
  224. this.writeUint32(jspb.utils.split64High);
  225. };
  226. /**
  227. * Writes a 8-bit integer to the buffer. Numbers outside the range
  228. * [-2^7,2^7) will be truncated.
  229. * @param {number} value The value to write.
  230. */
  231. jspb.BinaryEncoder.prototype.writeInt8 = function(value) {
  232. goog.asserts.assert(value == Math.floor(value));
  233. goog.asserts.assert((value >= -128) && (value < 128));
  234. this.buffer_.push((value >>> 0) & 0xFF);
  235. };
  236. /**
  237. * Writes a 16-bit integer to the buffer. Numbers outside the range
  238. * [-2^15,2^15) will be truncated.
  239. * @param {number} value The value to write.
  240. */
  241. jspb.BinaryEncoder.prototype.writeInt16 = function(value) {
  242. goog.asserts.assert(value == Math.floor(value));
  243. goog.asserts.assert((value >= -32768) && (value < 32768));
  244. this.buffer_.push((value >>> 0) & 0xFF);
  245. this.buffer_.push((value >>> 8) & 0xFF);
  246. };
  247. /**
  248. * Writes a 32-bit integer to the buffer. Numbers outside the range
  249. * [-2^31,2^31) will be truncated.
  250. * @param {number} value The value to write.
  251. */
  252. jspb.BinaryEncoder.prototype.writeInt32 = function(value) {
  253. goog.asserts.assert(value == Math.floor(value));
  254. goog.asserts.assert((value >= -jspb.BinaryConstants.TWO_TO_31) &&
  255. (value < jspb.BinaryConstants.TWO_TO_31));
  256. this.buffer_.push((value >>> 0) & 0xFF);
  257. this.buffer_.push((value >>> 8) & 0xFF);
  258. this.buffer_.push((value >>> 16) & 0xFF);
  259. this.buffer_.push((value >>> 24) & 0xFF);
  260. };
  261. /**
  262. * Writes a 64-bit integer to the buffer. Numbers outside the range
  263. * [-2^63,2^63) will be truncated.
  264. * @param {number} value The value to write.
  265. */
  266. jspb.BinaryEncoder.prototype.writeInt64 = function(value) {
  267. goog.asserts.assert(value == Math.floor(value));
  268. goog.asserts.assert((value >= -jspb.BinaryConstants.TWO_TO_63) &&
  269. (value < jspb.BinaryConstants.TWO_TO_63));
  270. jspb.utils.splitInt64(value);
  271. this.writeUint32(jspb.utils.split64Low);
  272. this.writeUint32(jspb.utils.split64High);
  273. };
  274. /**
  275. * Writes a single-precision floating point value to the buffer. Numbers
  276. * requiring more than 32 bits of precision will be truncated.
  277. * @param {number} value The value to write.
  278. */
  279. jspb.BinaryEncoder.prototype.writeFloat = function(value) {
  280. goog.asserts.assert((value >= -jspb.BinaryConstants.FLOAT32_MAX) &&
  281. (value <= jspb.BinaryConstants.FLOAT32_MAX));
  282. jspb.utils.splitFloat32(value);
  283. this.writeUint32(jspb.utils.split64Low);
  284. };
  285. /**
  286. * Writes a double-precision floating point value to the buffer. As this is
  287. * the native format used by JavaScript, no precision will be lost.
  288. * @param {number} value The value to write.
  289. */
  290. jspb.BinaryEncoder.prototype.writeDouble = function(value) {
  291. goog.asserts.assert((value >= -jspb.BinaryConstants.FLOAT64_MAX) &&
  292. (value <= jspb.BinaryConstants.FLOAT64_MAX));
  293. jspb.utils.splitFloat64(value);
  294. this.writeUint32(jspb.utils.split64Low);
  295. this.writeUint32(jspb.utils.split64High);
  296. };
  297. /**
  298. * Writes a boolean value to the buffer as a varint.
  299. * @param {boolean} value The value to write.
  300. */
  301. jspb.BinaryEncoder.prototype.writeBool = function(value) {
  302. goog.asserts.assert(goog.isBoolean(value));
  303. this.buffer_.push(value ? 1 : 0);
  304. };
  305. /**
  306. * Writes an enum value to the buffer as a varint.
  307. * @param {number} value The value to write.
  308. */
  309. jspb.BinaryEncoder.prototype.writeEnum = function(value) {
  310. goog.asserts.assert(value == Math.floor(value));
  311. goog.asserts.assert((value >= -jspb.BinaryConstants.TWO_TO_31) &&
  312. (value < jspb.BinaryConstants.TWO_TO_31));
  313. this.writeSignedVarint32(value);
  314. };
  315. /**
  316. * Writes an arbitrary byte array to the buffer.
  317. * @param {!Uint8Array} bytes The array of bytes to write.
  318. */
  319. jspb.BinaryEncoder.prototype.writeBytes = function(bytes) {
  320. this.buffer_.push.apply(this.buffer_, bytes);
  321. };
  322. /**
  323. * Writes a 64-bit hash string (8 characters @ 8 bits of data each) to the
  324. * buffer as a varint.
  325. * @param {string} hash The hash to write.
  326. */
  327. jspb.BinaryEncoder.prototype.writeVarintHash64 = function(hash) {
  328. jspb.utils.splitHash64(hash);
  329. this.writeSplitVarint64(jspb.utils.split64Low,
  330. jspb.utils.split64High);
  331. };
  332. /**
  333. * Writes a 64-bit hash string (8 characters @ 8 bits of data each) to the
  334. * buffer as a fixed64.
  335. * @param {string} hash The hash to write.
  336. */
  337. jspb.BinaryEncoder.prototype.writeFixedHash64 = function(hash) {
  338. jspb.utils.splitHash64(hash);
  339. this.writeUint32(jspb.utils.split64Low);
  340. this.writeUint32(jspb.utils.split64High);
  341. };
  342. /**
  343. * Writes a UTF16 Javascript string to the buffer encoded as UTF8.
  344. * TODO(aappleby): Add support for surrogate pairs, reject unpaired surrogates.
  345. * @param {string} value The string to write.
  346. * @return {number} The number of bytes used to encode the string.
  347. */
  348. jspb.BinaryEncoder.prototype.writeString = function(value) {
  349. var oldLength = this.buffer_.length;
  350. // UTF16 to UTF8 conversion loop swiped from goog.crypt.stringToUtf8ByteArray.
  351. for (var i = 0; i < value.length; i++) {
  352. var c = value.charCodeAt(i);
  353. if (c < 128) {
  354. this.buffer_.push(c);
  355. } else if (c < 2048) {
  356. this.buffer_.push((c >> 6) | 192);
  357. this.buffer_.push((c & 63) | 128);
  358. } else {
  359. this.buffer_.push((c >> 12) | 224);
  360. this.buffer_.push(((c >> 6) & 63) | 128);
  361. this.buffer_.push((c & 63) | 128);
  362. }
  363. }
  364. var length = this.buffer_.length - oldLength;
  365. return length;
  366. };