/thirdparty/breakpad/third_party/protobuf/protobuf/java/src/main/java/com/google/protobuf/CodedOutputStream.java

http://github.com/tomahawk-player/tomahawk · Java · 1081 lines · 548 code · 125 blank · 408 comment · 63 complexity · d86a99f7fc89cfd288231a1fa541d105 MD5 · raw file

  1. // Protocol Buffers - Google's data interchange format
  2. // Copyright 2008 Google Inc. All rights reserved.
  3. // http://code.google.com/p/protobuf/
  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. package com.google.protobuf;
  31. import java.io.OutputStream;
  32. import java.io.IOException;
  33. import java.io.UnsupportedEncodingException;
  34. import java.io.InputStream;
  35. /**
  36. * Encodes and writes protocol message fields.
  37. *
  38. * <p>This class contains two kinds of methods: methods that write specific
  39. * protocol message constructs and field types (e.g. {@link #writeTag} and
  40. * {@link #writeInt32}) and methods that write low-level values (e.g.
  41. * {@link #writeRawVarint32} and {@link #writeRawBytes}). If you are
  42. * writing encoded protocol messages, you should use the former methods, but if
  43. * you are writing some other format of your own design, use the latter.
  44. *
  45. * <p>This class is totally unsynchronized.
  46. *
  47. * @author kneton@google.com Kenton Varda
  48. */
  49. public final class CodedOutputStream {
  50. private final byte[] buffer;
  51. private final int limit;
  52. private int position;
  53. private final OutputStream output;
  54. /**
  55. * The buffer size used in {@link #newInstance(OutputStream)}.
  56. */
  57. public static final int DEFAULT_BUFFER_SIZE = 4096;
  58. /**
  59. * Returns the buffer size to efficiently write dataLength bytes to this
  60. * CodedOutputStream. Used by AbstractMessageLite.
  61. *
  62. * @return the buffer size to efficiently write dataLength bytes to this
  63. * CodedOutputStream.
  64. */
  65. static int computePreferredBufferSize(int dataLength) {
  66. if (dataLength > DEFAULT_BUFFER_SIZE) return DEFAULT_BUFFER_SIZE;
  67. return dataLength;
  68. }
  69. private CodedOutputStream(final byte[] buffer, final int offset,
  70. final int length) {
  71. output = null;
  72. this.buffer = buffer;
  73. position = offset;
  74. limit = offset + length;
  75. }
  76. private CodedOutputStream(final OutputStream output, final byte[] buffer) {
  77. this.output = output;
  78. this.buffer = buffer;
  79. position = 0;
  80. limit = buffer.length;
  81. }
  82. /**
  83. * Create a new {@code CodedOutputStream} wrapping the given
  84. * {@code OutputStream}.
  85. */
  86. public static CodedOutputStream newInstance(final OutputStream output) {
  87. return newInstance(output, DEFAULT_BUFFER_SIZE);
  88. }
  89. /**
  90. * Create a new {@code CodedOutputStream} wrapping the given
  91. * {@code OutputStream} with a given buffer size.
  92. */
  93. public static CodedOutputStream newInstance(final OutputStream output,
  94. final int bufferSize) {
  95. return new CodedOutputStream(output, new byte[bufferSize]);
  96. }
  97. /**
  98. * Create a new {@code CodedOutputStream} that writes directly to the given
  99. * byte array. If more bytes are written than fit in the array,
  100. * {@link OutOfSpaceException} will be thrown. Writing directly to a flat
  101. * array is faster than writing to an {@code OutputStream}. See also
  102. * {@link ByteString#newCodedBuilder}.
  103. */
  104. public static CodedOutputStream newInstance(final byte[] flatArray) {
  105. return newInstance(flatArray, 0, flatArray.length);
  106. }
  107. /**
  108. * Create a new {@code CodedOutputStream} that writes directly to the given
  109. * byte array slice. If more bytes are written than fit in the slice,
  110. * {@link OutOfSpaceException} will be thrown. Writing directly to a flat
  111. * array is faster than writing to an {@code OutputStream}. See also
  112. * {@link ByteString#newCodedBuilder}.
  113. */
  114. public static CodedOutputStream newInstance(final byte[] flatArray,
  115. final int offset,
  116. final int length) {
  117. return new CodedOutputStream(flatArray, offset, length);
  118. }
  119. // -----------------------------------------------------------------
  120. /** Write a {@code double} field, including tag, to the stream. */
  121. public void writeDouble(final int fieldNumber, final double value)
  122. throws IOException {
  123. writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED64);
  124. writeDoubleNoTag(value);
  125. }
  126. /** Write a {@code float} field, including tag, to the stream. */
  127. public void writeFloat(final int fieldNumber, final float value)
  128. throws IOException {
  129. writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED32);
  130. writeFloatNoTag(value);
  131. }
  132. /** Write a {@code uint64} field, including tag, to the stream. */
  133. public void writeUInt64(final int fieldNumber, final long value)
  134. throws IOException {
  135. writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
  136. writeUInt64NoTag(value);
  137. }
  138. /** Write an {@code int64} field, including tag, to the stream. */
  139. public void writeInt64(final int fieldNumber, final long value)
  140. throws IOException {
  141. writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
  142. writeInt64NoTag(value);
  143. }
  144. /** Write an {@code int32} field, including tag, to the stream. */
  145. public void writeInt32(final int fieldNumber, final int value)
  146. throws IOException {
  147. writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
  148. writeInt32NoTag(value);
  149. }
  150. /** Write a {@code fixed64} field, including tag, to the stream. */
  151. public void writeFixed64(final int fieldNumber, final long value)
  152. throws IOException {
  153. writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED64);
  154. writeFixed64NoTag(value);
  155. }
  156. /** Write a {@code fixed32} field, including tag, to the stream. */
  157. public void writeFixed32(final int fieldNumber, final int value)
  158. throws IOException {
  159. writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED32);
  160. writeFixed32NoTag(value);
  161. }
  162. /** Write a {@code bool} field, including tag, to the stream. */
  163. public void writeBool(final int fieldNumber, final boolean value)
  164. throws IOException {
  165. writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
  166. writeBoolNoTag(value);
  167. }
  168. /** Write a {@code string} field, including tag, to the stream. */
  169. public void writeString(final int fieldNumber, final String value)
  170. throws IOException {
  171. writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED);
  172. writeStringNoTag(value);
  173. }
  174. /** Write a {@code group} field, including tag, to the stream. */
  175. public void writeGroup(final int fieldNumber, final MessageLite value)
  176. throws IOException {
  177. writeTag(fieldNumber, WireFormat.WIRETYPE_START_GROUP);
  178. writeGroupNoTag(value);
  179. writeTag(fieldNumber, WireFormat.WIRETYPE_END_GROUP);
  180. }
  181. /**
  182. * Write a group represented by an {@link UnknownFieldSet}.
  183. *
  184. * @deprecated UnknownFieldSet now implements MessageLite, so you can just
  185. * call {@link #writeGroup}.
  186. */
  187. @Deprecated
  188. public void writeUnknownGroup(final int fieldNumber,
  189. final MessageLite value)
  190. throws IOException {
  191. writeGroup(fieldNumber, value);
  192. }
  193. /** Write an embedded message field, including tag, to the stream. */
  194. public void writeMessage(final int fieldNumber, final MessageLite value)
  195. throws IOException {
  196. writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED);
  197. writeMessageNoTag(value);
  198. }
  199. /** Write a {@code bytes} field, including tag, to the stream. */
  200. public void writeBytes(final int fieldNumber, final ByteString value)
  201. throws IOException {
  202. writeTag(fieldNumber, WireFormat.WIRETYPE_LENGTH_DELIMITED);
  203. writeBytesNoTag(value);
  204. }
  205. /** Write a {@code uint32} field, including tag, to the stream. */
  206. public void writeUInt32(final int fieldNumber, final int value)
  207. throws IOException {
  208. writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
  209. writeUInt32NoTag(value);
  210. }
  211. /**
  212. * Write an enum field, including tag, to the stream. Caller is responsible
  213. * for converting the enum value to its numeric value.
  214. */
  215. public void writeEnum(final int fieldNumber, final int value)
  216. throws IOException {
  217. writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
  218. writeEnumNoTag(value);
  219. }
  220. /** Write an {@code sfixed32} field, including tag, to the stream. */
  221. public void writeSFixed32(final int fieldNumber, final int value)
  222. throws IOException {
  223. writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED32);
  224. writeSFixed32NoTag(value);
  225. }
  226. /** Write an {@code sfixed64} field, including tag, to the stream. */
  227. public void writeSFixed64(final int fieldNumber, final long value)
  228. throws IOException {
  229. writeTag(fieldNumber, WireFormat.WIRETYPE_FIXED64);
  230. writeSFixed64NoTag(value);
  231. }
  232. /** Write an {@code sint32} field, including tag, to the stream. */
  233. public void writeSInt32(final int fieldNumber, final int value)
  234. throws IOException {
  235. writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
  236. writeSInt32NoTag(value);
  237. }
  238. /** Write an {@code sint64} field, including tag, to the stream. */
  239. public void writeSInt64(final int fieldNumber, final long value)
  240. throws IOException {
  241. writeTag(fieldNumber, WireFormat.WIRETYPE_VARINT);
  242. writeSInt64NoTag(value);
  243. }
  244. /**
  245. * Write a MessageSet extension field to the stream. For historical reasons,
  246. * the wire format differs from normal fields.
  247. */
  248. public void writeMessageSetExtension(final int fieldNumber,
  249. final MessageLite value)
  250. throws IOException {
  251. writeTag(WireFormat.MESSAGE_SET_ITEM, WireFormat.WIRETYPE_START_GROUP);
  252. writeUInt32(WireFormat.MESSAGE_SET_TYPE_ID, fieldNumber);
  253. writeMessage(WireFormat.MESSAGE_SET_MESSAGE, value);
  254. writeTag(WireFormat.MESSAGE_SET_ITEM, WireFormat.WIRETYPE_END_GROUP);
  255. }
  256. /**
  257. * Write an unparsed MessageSet extension field to the stream. For
  258. * historical reasons, the wire format differs from normal fields.
  259. */
  260. public void writeRawMessageSetExtension(final int fieldNumber,
  261. final ByteString value)
  262. throws IOException {
  263. writeTag(WireFormat.MESSAGE_SET_ITEM, WireFormat.WIRETYPE_START_GROUP);
  264. writeUInt32(WireFormat.MESSAGE_SET_TYPE_ID, fieldNumber);
  265. writeBytes(WireFormat.MESSAGE_SET_MESSAGE, value);
  266. writeTag(WireFormat.MESSAGE_SET_ITEM, WireFormat.WIRETYPE_END_GROUP);
  267. }
  268. // -----------------------------------------------------------------
  269. /** Write a {@code double} field to the stream. */
  270. public void writeDoubleNoTag(final double value) throws IOException {
  271. writeRawLittleEndian64(Double.doubleToRawLongBits(value));
  272. }
  273. /** Write a {@code float} field to the stream. */
  274. public void writeFloatNoTag(final float value) throws IOException {
  275. writeRawLittleEndian32(Float.floatToRawIntBits(value));
  276. }
  277. /** Write a {@code uint64} field to the stream. */
  278. public void writeUInt64NoTag(final long value) throws IOException {
  279. writeRawVarint64(value);
  280. }
  281. /** Write an {@code int64} field to the stream. */
  282. public void writeInt64NoTag(final long value) throws IOException {
  283. writeRawVarint64(value);
  284. }
  285. /** Write an {@code int32} field to the stream. */
  286. public void writeInt32NoTag(final int value) throws IOException {
  287. if (value >= 0) {
  288. writeRawVarint32(value);
  289. } else {
  290. // Must sign-extend.
  291. writeRawVarint64(value);
  292. }
  293. }
  294. /** Write a {@code fixed64} field to the stream. */
  295. public void writeFixed64NoTag(final long value) throws IOException {
  296. writeRawLittleEndian64(value);
  297. }
  298. /** Write a {@code fixed32} field to the stream. */
  299. public void writeFixed32NoTag(final int value) throws IOException {
  300. writeRawLittleEndian32(value);
  301. }
  302. /** Write a {@code bool} field to the stream. */
  303. public void writeBoolNoTag(final boolean value) throws IOException {
  304. writeRawByte(value ? 1 : 0);
  305. }
  306. /** Write a {@code string} field to the stream. */
  307. public void writeStringNoTag(final String value) throws IOException {
  308. // Unfortunately there does not appear to be any way to tell Java to encode
  309. // UTF-8 directly into our buffer, so we have to let it create its own byte
  310. // array and then copy.
  311. final byte[] bytes = value.getBytes("UTF-8");
  312. writeRawVarint32(bytes.length);
  313. writeRawBytes(bytes);
  314. }
  315. /** Write a {@code group} field to the stream. */
  316. public void writeGroupNoTag(final MessageLite value) throws IOException {
  317. value.writeTo(this);
  318. }
  319. /**
  320. * Write a group represented by an {@link UnknownFieldSet}.
  321. *
  322. * @deprecated UnknownFieldSet now implements MessageLite, so you can just
  323. * call {@link #writeGroupNoTag}.
  324. */
  325. @Deprecated
  326. public void writeUnknownGroupNoTag(final MessageLite value)
  327. throws IOException {
  328. writeGroupNoTag(value);
  329. }
  330. /** Write an embedded message field to the stream. */
  331. public void writeMessageNoTag(final MessageLite value) throws IOException {
  332. writeRawVarint32(value.getSerializedSize());
  333. value.writeTo(this);
  334. }
  335. /** Write a {@code bytes} field to the stream. */
  336. public void writeBytesNoTag(final ByteString value) throws IOException {
  337. writeRawVarint32(value.size());
  338. writeRawBytes(value);
  339. }
  340. /** Write a {@code uint32} field to the stream. */
  341. public void writeUInt32NoTag(final int value) throws IOException {
  342. writeRawVarint32(value);
  343. }
  344. /**
  345. * Write an enum field to the stream. Caller is responsible
  346. * for converting the enum value to its numeric value.
  347. */
  348. public void writeEnumNoTag(final int value) throws IOException {
  349. writeInt32NoTag(value);
  350. }
  351. /** Write an {@code sfixed32} field to the stream. */
  352. public void writeSFixed32NoTag(final int value) throws IOException {
  353. writeRawLittleEndian32(value);
  354. }
  355. /** Write an {@code sfixed64} field to the stream. */
  356. public void writeSFixed64NoTag(final long value) throws IOException {
  357. writeRawLittleEndian64(value);
  358. }
  359. /** Write an {@code sint32} field to the stream. */
  360. public void writeSInt32NoTag(final int value) throws IOException {
  361. writeRawVarint32(encodeZigZag32(value));
  362. }
  363. /** Write an {@code sint64} field to the stream. */
  364. public void writeSInt64NoTag(final long value) throws IOException {
  365. writeRawVarint64(encodeZigZag64(value));
  366. }
  367. // =================================================================
  368. /**
  369. * Compute the number of bytes that would be needed to encode a
  370. * {@code double} field, including tag.
  371. */
  372. public static int computeDoubleSize(final int fieldNumber,
  373. final double value) {
  374. return computeTagSize(fieldNumber) + computeDoubleSizeNoTag(value);
  375. }
  376. /**
  377. * Compute the number of bytes that would be needed to encode a
  378. * {@code float} field, including tag.
  379. */
  380. public static int computeFloatSize(final int fieldNumber, final float value) {
  381. return computeTagSize(fieldNumber) + computeFloatSizeNoTag(value);
  382. }
  383. /**
  384. * Compute the number of bytes that would be needed to encode a
  385. * {@code uint64} field, including tag.
  386. */
  387. public static int computeUInt64Size(final int fieldNumber, final long value) {
  388. return computeTagSize(fieldNumber) + computeUInt64SizeNoTag(value);
  389. }
  390. /**
  391. * Compute the number of bytes that would be needed to encode an
  392. * {@code int64} field, including tag.
  393. */
  394. public static int computeInt64Size(final int fieldNumber, final long value) {
  395. return computeTagSize(fieldNumber) + computeInt64SizeNoTag(value);
  396. }
  397. /**
  398. * Compute the number of bytes that would be needed to encode an
  399. * {@code int32} field, including tag.
  400. */
  401. public static int computeInt32Size(final int fieldNumber, final int value) {
  402. return computeTagSize(fieldNumber) + computeInt32SizeNoTag(value);
  403. }
  404. /**
  405. * Compute the number of bytes that would be needed to encode a
  406. * {@code fixed64} field, including tag.
  407. */
  408. public static int computeFixed64Size(final int fieldNumber,
  409. final long value) {
  410. return computeTagSize(fieldNumber) + computeFixed64SizeNoTag(value);
  411. }
  412. /**
  413. * Compute the number of bytes that would be needed to encode a
  414. * {@code fixed32} field, including tag.
  415. */
  416. public static int computeFixed32Size(final int fieldNumber,
  417. final int value) {
  418. return computeTagSize(fieldNumber) + computeFixed32SizeNoTag(value);
  419. }
  420. /**
  421. * Compute the number of bytes that would be needed to encode a
  422. * {@code bool} field, including tag.
  423. */
  424. public static int computeBoolSize(final int fieldNumber,
  425. final boolean value) {
  426. return computeTagSize(fieldNumber) + computeBoolSizeNoTag(value);
  427. }
  428. /**
  429. * Compute the number of bytes that would be needed to encode a
  430. * {@code string} field, including tag.
  431. */
  432. public static int computeStringSize(final int fieldNumber,
  433. final String value) {
  434. return computeTagSize(fieldNumber) + computeStringSizeNoTag(value);
  435. }
  436. /**
  437. * Compute the number of bytes that would be needed to encode a
  438. * {@code group} field, including tag.
  439. */
  440. public static int computeGroupSize(final int fieldNumber,
  441. final MessageLite value) {
  442. return computeTagSize(fieldNumber) * 2 + computeGroupSizeNoTag(value);
  443. }
  444. /**
  445. * Compute the number of bytes that would be needed to encode a
  446. * {@code group} field represented by an {@code UnknownFieldSet}, including
  447. * tag.
  448. *
  449. * @deprecated UnknownFieldSet now implements MessageLite, so you can just
  450. * call {@link #computeGroupSize}.
  451. */
  452. @Deprecated
  453. public static int computeUnknownGroupSize(final int fieldNumber,
  454. final MessageLite value) {
  455. return computeGroupSize(fieldNumber, value);
  456. }
  457. /**
  458. * Compute the number of bytes that would be needed to encode an
  459. * embedded message field, including tag.
  460. */
  461. public static int computeMessageSize(final int fieldNumber,
  462. final MessageLite value) {
  463. return computeTagSize(fieldNumber) + computeMessageSizeNoTag(value);
  464. }
  465. /**
  466. * Compute the number of bytes that would be needed to encode a
  467. * {@code bytes} field, including tag.
  468. */
  469. public static int computeBytesSize(final int fieldNumber,
  470. final ByteString value) {
  471. return computeTagSize(fieldNumber) + computeBytesSizeNoTag(value);
  472. }
  473. /**
  474. * Compute the number of bytes that would be needed to encode a
  475. * {@code uint32} field, including tag.
  476. */
  477. public static int computeUInt32Size(final int fieldNumber, final int value) {
  478. return computeTagSize(fieldNumber) + computeUInt32SizeNoTag(value);
  479. }
  480. /**
  481. * Compute the number of bytes that would be needed to encode an
  482. * enum field, including tag. Caller is responsible for converting the
  483. * enum value to its numeric value.
  484. */
  485. public static int computeEnumSize(final int fieldNumber, final int value) {
  486. return computeTagSize(fieldNumber) + computeEnumSizeNoTag(value);
  487. }
  488. /**
  489. * Compute the number of bytes that would be needed to encode an
  490. * {@code sfixed32} field, including tag.
  491. */
  492. public static int computeSFixed32Size(final int fieldNumber,
  493. final int value) {
  494. return computeTagSize(fieldNumber) + computeSFixed32SizeNoTag(value);
  495. }
  496. /**
  497. * Compute the number of bytes that would be needed to encode an
  498. * {@code sfixed64} field, including tag.
  499. */
  500. public static int computeSFixed64Size(final int fieldNumber,
  501. final long value) {
  502. return computeTagSize(fieldNumber) + computeSFixed64SizeNoTag(value);
  503. }
  504. /**
  505. * Compute the number of bytes that would be needed to encode an
  506. * {@code sint32} field, including tag.
  507. */
  508. public static int computeSInt32Size(final int fieldNumber, final int value) {
  509. return computeTagSize(fieldNumber) + computeSInt32SizeNoTag(value);
  510. }
  511. /**
  512. * Compute the number of bytes that would be needed to encode an
  513. * {@code sint64} field, including tag.
  514. */
  515. public static int computeSInt64Size(final int fieldNumber, final long value) {
  516. return computeTagSize(fieldNumber) + computeSInt64SizeNoTag(value);
  517. }
  518. /**
  519. * Compute the number of bytes that would be needed to encode a
  520. * MessageSet extension to the stream. For historical reasons,
  521. * the wire format differs from normal fields.
  522. */
  523. public static int computeMessageSetExtensionSize(
  524. final int fieldNumber, final MessageLite value) {
  525. return computeTagSize(WireFormat.MESSAGE_SET_ITEM) * 2 +
  526. computeUInt32Size(WireFormat.MESSAGE_SET_TYPE_ID, fieldNumber) +
  527. computeMessageSize(WireFormat.MESSAGE_SET_MESSAGE, value);
  528. }
  529. /**
  530. * Compute the number of bytes that would be needed to encode an
  531. * unparsed MessageSet extension field to the stream. For
  532. * historical reasons, the wire format differs from normal fields.
  533. */
  534. public static int computeRawMessageSetExtensionSize(
  535. final int fieldNumber, final ByteString value) {
  536. return computeTagSize(WireFormat.MESSAGE_SET_ITEM) * 2 +
  537. computeUInt32Size(WireFormat.MESSAGE_SET_TYPE_ID, fieldNumber) +
  538. computeBytesSize(WireFormat.MESSAGE_SET_MESSAGE, value);
  539. }
  540. // -----------------------------------------------------------------
  541. /**
  542. * Compute the number of bytes that would be needed to encode a
  543. * {@code double} field, including tag.
  544. */
  545. public static int computeDoubleSizeNoTag(final double value) {
  546. return LITTLE_ENDIAN_64_SIZE;
  547. }
  548. /**
  549. * Compute the number of bytes that would be needed to encode a
  550. * {@code float} field, including tag.
  551. */
  552. public static int computeFloatSizeNoTag(final float value) {
  553. return LITTLE_ENDIAN_32_SIZE;
  554. }
  555. /**
  556. * Compute the number of bytes that would be needed to encode a
  557. * {@code uint64} field, including tag.
  558. */
  559. public static int computeUInt64SizeNoTag(final long value) {
  560. return computeRawVarint64Size(value);
  561. }
  562. /**
  563. * Compute the number of bytes that would be needed to encode an
  564. * {@code int64} field, including tag.
  565. */
  566. public static int computeInt64SizeNoTag(final long value) {
  567. return computeRawVarint64Size(value);
  568. }
  569. /**
  570. * Compute the number of bytes that would be needed to encode an
  571. * {@code int32} field, including tag.
  572. */
  573. public static int computeInt32SizeNoTag(final int value) {
  574. if (value >= 0) {
  575. return computeRawVarint32Size(value);
  576. } else {
  577. // Must sign-extend.
  578. return 10;
  579. }
  580. }
  581. /**
  582. * Compute the number of bytes that would be needed to encode a
  583. * {@code fixed64} field.
  584. */
  585. public static int computeFixed64SizeNoTag(final long value) {
  586. return LITTLE_ENDIAN_64_SIZE;
  587. }
  588. /**
  589. * Compute the number of bytes that would be needed to encode a
  590. * {@code fixed32} field.
  591. */
  592. public static int computeFixed32SizeNoTag(final int value) {
  593. return LITTLE_ENDIAN_32_SIZE;
  594. }
  595. /**
  596. * Compute the number of bytes that would be needed to encode a
  597. * {@code bool} field.
  598. */
  599. public static int computeBoolSizeNoTag(final boolean value) {
  600. return 1;
  601. }
  602. /**
  603. * Compute the number of bytes that would be needed to encode a
  604. * {@code string} field.
  605. */
  606. public static int computeStringSizeNoTag(final String value) {
  607. try {
  608. final byte[] bytes = value.getBytes("UTF-8");
  609. return computeRawVarint32Size(bytes.length) +
  610. bytes.length;
  611. } catch (UnsupportedEncodingException e) {
  612. throw new RuntimeException("UTF-8 not supported.", e);
  613. }
  614. }
  615. /**
  616. * Compute the number of bytes that would be needed to encode a
  617. * {@code group} field.
  618. */
  619. public static int computeGroupSizeNoTag(final MessageLite value) {
  620. return value.getSerializedSize();
  621. }
  622. /**
  623. * Compute the number of bytes that would be needed to encode a
  624. * {@code group} field represented by an {@code UnknownFieldSet}, including
  625. * tag.
  626. *
  627. * @deprecated UnknownFieldSet now implements MessageLite, so you can just
  628. * call {@link #computeUnknownGroupSizeNoTag}.
  629. */
  630. @Deprecated
  631. public static int computeUnknownGroupSizeNoTag(final MessageLite value) {
  632. return computeGroupSizeNoTag(value);
  633. }
  634. /**
  635. * Compute the number of bytes that would be needed to encode an embedded
  636. * message field.
  637. */
  638. public static int computeMessageSizeNoTag(final MessageLite value) {
  639. final int size = value.getSerializedSize();
  640. return computeRawVarint32Size(size) + size;
  641. }
  642. /**
  643. * Compute the number of bytes that would be needed to encode a
  644. * {@code bytes} field.
  645. */
  646. public static int computeBytesSizeNoTag(final ByteString value) {
  647. return computeRawVarint32Size(value.size()) +
  648. value.size();
  649. }
  650. /**
  651. * Compute the number of bytes that would be needed to encode a
  652. * {@code uint32} field.
  653. */
  654. public static int computeUInt32SizeNoTag(final int value) {
  655. return computeRawVarint32Size(value);
  656. }
  657. /**
  658. * Compute the number of bytes that would be needed to encode an enum field.
  659. * Caller is responsible for converting the enum value to its numeric value.
  660. */
  661. public static int computeEnumSizeNoTag(final int value) {
  662. return computeInt32SizeNoTag(value);
  663. }
  664. /**
  665. * Compute the number of bytes that would be needed to encode an
  666. * {@code sfixed32} field.
  667. */
  668. public static int computeSFixed32SizeNoTag(final int value) {
  669. return LITTLE_ENDIAN_32_SIZE;
  670. }
  671. /**
  672. * Compute the number of bytes that would be needed to encode an
  673. * {@code sfixed64} field.
  674. */
  675. public static int computeSFixed64SizeNoTag(final long value) {
  676. return LITTLE_ENDIAN_64_SIZE;
  677. }
  678. /**
  679. * Compute the number of bytes that would be needed to encode an
  680. * {@code sint32} field.
  681. */
  682. public static int computeSInt32SizeNoTag(final int value) {
  683. return computeRawVarint32Size(encodeZigZag32(value));
  684. }
  685. /**
  686. * Compute the number of bytes that would be needed to encode an
  687. * {@code sint64} field.
  688. */
  689. public static int computeSInt64SizeNoTag(final long value) {
  690. return computeRawVarint64Size(encodeZigZag64(value));
  691. }
  692. // =================================================================
  693. /**
  694. * Internal helper that writes the current buffer to the output. The
  695. * buffer position is reset to its initial value when this returns.
  696. */
  697. private void refreshBuffer() throws IOException {
  698. if (output == null) {
  699. // We're writing to a single buffer.
  700. throw new OutOfSpaceException();
  701. }
  702. // Since we have an output stream, this is our buffer
  703. // and buffer offset == 0
  704. output.write(buffer, 0, position);
  705. position = 0;
  706. }
  707. /**
  708. * Flushes the stream and forces any buffered bytes to be written. This
  709. * does not flush the underlying OutputStream.
  710. */
  711. public void flush() throws IOException {
  712. if (output != null) {
  713. refreshBuffer();
  714. }
  715. }
  716. /**
  717. * If writing to a flat array, return the space left in the array.
  718. * Otherwise, throws {@code UnsupportedOperationException}.
  719. */
  720. public int spaceLeft() {
  721. if (output == null) {
  722. return limit - position;
  723. } else {
  724. throw new UnsupportedOperationException(
  725. "spaceLeft() can only be called on CodedOutputStreams that are " +
  726. "writing to a flat array.");
  727. }
  728. }
  729. /**
  730. * Verifies that {@link #spaceLeft()} returns zero. It's common to create
  731. * a byte array that is exactly big enough to hold a message, then write to
  732. * it with a {@code CodedOutputStream}. Calling {@code checkNoSpaceLeft()}
  733. * after writing verifies that the message was actually as big as expected,
  734. * which can help catch bugs.
  735. */
  736. public void checkNoSpaceLeft() {
  737. if (spaceLeft() != 0) {
  738. throw new IllegalStateException(
  739. "Did not write as much data as expected.");
  740. }
  741. }
  742. /**
  743. * If you create a CodedOutputStream around a simple flat array, you must
  744. * not attempt to write more bytes than the array has space. Otherwise,
  745. * this exception will be thrown.
  746. */
  747. public static class OutOfSpaceException extends IOException {
  748. private static final long serialVersionUID = -6947486886997889499L;
  749. OutOfSpaceException() {
  750. super("CodedOutputStream was writing to a flat byte array and ran " +
  751. "out of space.");
  752. }
  753. }
  754. /** Write a single byte. */
  755. public void writeRawByte(final byte value) throws IOException {
  756. if (position == limit) {
  757. refreshBuffer();
  758. }
  759. buffer[position++] = value;
  760. }
  761. /** Write a single byte, represented by an integer value. */
  762. public void writeRawByte(final int value) throws IOException {
  763. writeRawByte((byte) value);
  764. }
  765. /** Write a byte string. */
  766. public void writeRawBytes(final ByteString value) throws IOException {
  767. writeRawBytes(value, 0, value.size());
  768. }
  769. /** Write an array of bytes. */
  770. public void writeRawBytes(final byte[] value) throws IOException {
  771. writeRawBytes(value, 0, value.length);
  772. }
  773. /** Write part of an array of bytes. */
  774. public void writeRawBytes(final byte[] value, int offset, int length)
  775. throws IOException {
  776. if (limit - position >= length) {
  777. // We have room in the current buffer.
  778. System.arraycopy(value, offset, buffer, position, length);
  779. position += length;
  780. } else {
  781. // Write extends past current buffer. Fill the rest of this buffer and
  782. // flush.
  783. final int bytesWritten = limit - position;
  784. System.arraycopy(value, offset, buffer, position, bytesWritten);
  785. offset += bytesWritten;
  786. length -= bytesWritten;
  787. position = limit;
  788. refreshBuffer();
  789. // Now deal with the rest.
  790. // Since we have an output stream, this is our buffer
  791. // and buffer offset == 0
  792. if (length <= limit) {
  793. // Fits in new buffer.
  794. System.arraycopy(value, offset, buffer, 0, length);
  795. position = length;
  796. } else {
  797. // Write is very big. Let's do it all at once.
  798. output.write(value, offset, length);
  799. }
  800. }
  801. }
  802. /** Write part of a byte string. */
  803. public void writeRawBytes(final ByteString value, int offset, int length)
  804. throws IOException {
  805. if (limit - position >= length) {
  806. // We have room in the current buffer.
  807. value.copyTo(buffer, offset, position, length);
  808. position += length;
  809. } else {
  810. // Write extends past current buffer. Fill the rest of this buffer and
  811. // flush.
  812. final int bytesWritten = limit - position;
  813. value.copyTo(buffer, offset, position, bytesWritten);
  814. offset += bytesWritten;
  815. length -= bytesWritten;
  816. position = limit;
  817. refreshBuffer();
  818. // Now deal with the rest.
  819. // Since we have an output stream, this is our buffer
  820. // and buffer offset == 0
  821. if (length <= limit) {
  822. // Fits in new buffer.
  823. value.copyTo(buffer, offset, 0, length);
  824. position = length;
  825. } else {
  826. // Write is very big, but we can't do it all at once without allocating
  827. // an a copy of the byte array since ByteString does not give us access
  828. // to the underlying bytes. Use the InputStream interface on the
  829. // ByteString and our buffer to copy between the two.
  830. InputStream inputStreamFrom = value.newInput();
  831. if (offset != inputStreamFrom.skip(offset)) {
  832. throw new IllegalStateException("Skip failed? Should never happen.");
  833. }
  834. // Use the buffer as the temporary buffer to avoid allocating memory.
  835. while (length > 0) {
  836. int bytesToRead = Math.min(length, limit);
  837. int bytesRead = inputStreamFrom.read(buffer, 0, bytesToRead);
  838. if (bytesRead != bytesToRead) {
  839. throw new IllegalStateException("Read failed? Should never happen");
  840. }
  841. output.write(buffer, 0, bytesRead);
  842. length -= bytesRead;
  843. }
  844. }
  845. }
  846. }
  847. /** Encode and write a tag. */
  848. public void writeTag(final int fieldNumber, final int wireType)
  849. throws IOException {
  850. writeRawVarint32(WireFormat.makeTag(fieldNumber, wireType));
  851. }
  852. /** Compute the number of bytes that would be needed to encode a tag. */
  853. public static int computeTagSize(final int fieldNumber) {
  854. return computeRawVarint32Size(WireFormat.makeTag(fieldNumber, 0));
  855. }
  856. /**
  857. * Encode and write a varint. {@code value} is treated as
  858. * unsigned, so it won't be sign-extended if negative.
  859. */
  860. public void writeRawVarint32(int value) throws IOException {
  861. while (true) {
  862. if ((value & ~0x7F) == 0) {
  863. writeRawByte(value);
  864. return;
  865. } else {
  866. writeRawByte((value & 0x7F) | 0x80);
  867. value >>>= 7;
  868. }
  869. }
  870. }
  871. /**
  872. * Compute the number of bytes that would be needed to encode a varint.
  873. * {@code value} is treated as unsigned, so it won't be sign-extended if
  874. * negative.
  875. */
  876. public static int computeRawVarint32Size(final int value) {
  877. if ((value & (0xffffffff << 7)) == 0) return 1;
  878. if ((value & (0xffffffff << 14)) == 0) return 2;
  879. if ((value & (0xffffffff << 21)) == 0) return 3;
  880. if ((value & (0xffffffff << 28)) == 0) return 4;
  881. return 5;
  882. }
  883. /** Encode and write a varint. */
  884. public void writeRawVarint64(long value) throws IOException {
  885. while (true) {
  886. if ((value & ~0x7FL) == 0) {
  887. writeRawByte((int)value);
  888. return;
  889. } else {
  890. writeRawByte(((int)value & 0x7F) | 0x80);
  891. value >>>= 7;
  892. }
  893. }
  894. }
  895. /** Compute the number of bytes that would be needed to encode a varint. */
  896. public static int computeRawVarint64Size(final long value) {
  897. if ((value & (0xffffffffffffffffL << 7)) == 0) return 1;
  898. if ((value & (0xffffffffffffffffL << 14)) == 0) return 2;
  899. if ((value & (0xffffffffffffffffL << 21)) == 0) return 3;
  900. if ((value & (0xffffffffffffffffL << 28)) == 0) return 4;
  901. if ((value & (0xffffffffffffffffL << 35)) == 0) return 5;
  902. if ((value & (0xffffffffffffffffL << 42)) == 0) return 6;
  903. if ((value & (0xffffffffffffffffL << 49)) == 0) return 7;
  904. if ((value & (0xffffffffffffffffL << 56)) == 0) return 8;
  905. if ((value & (0xffffffffffffffffL << 63)) == 0) return 9;
  906. return 10;
  907. }
  908. /** Write a little-endian 32-bit integer. */
  909. public void writeRawLittleEndian32(final int value) throws IOException {
  910. writeRawByte((value ) & 0xFF);
  911. writeRawByte((value >> 8) & 0xFF);
  912. writeRawByte((value >> 16) & 0xFF);
  913. writeRawByte((value >> 24) & 0xFF);
  914. }
  915. public static final int LITTLE_ENDIAN_32_SIZE = 4;
  916. /** Write a little-endian 64-bit integer. */
  917. public void writeRawLittleEndian64(final long value) throws IOException {
  918. writeRawByte((int)(value ) & 0xFF);
  919. writeRawByte((int)(value >> 8) & 0xFF);
  920. writeRawByte((int)(value >> 16) & 0xFF);
  921. writeRawByte((int)(value >> 24) & 0xFF);
  922. writeRawByte((int)(value >> 32) & 0xFF);
  923. writeRawByte((int)(value >> 40) & 0xFF);
  924. writeRawByte((int)(value >> 48) & 0xFF);
  925. writeRawByte((int)(value >> 56) & 0xFF);
  926. }
  927. public static final int LITTLE_ENDIAN_64_SIZE = 8;
  928. /**
  929. * Encode a ZigZag-encoded 32-bit value. ZigZag encodes signed integers
  930. * into values that can be efficiently encoded with varint. (Otherwise,
  931. * negative values must be sign-extended to 64 bits to be varint encoded,
  932. * thus always taking 10 bytes on the wire.)
  933. *
  934. * @param n A signed 32-bit integer.
  935. * @return An unsigned 32-bit integer, stored in a signed int because
  936. * Java has no explicit unsigned support.
  937. */
  938. public static int encodeZigZag32(final int n) {
  939. // Note: the right-shift must be arithmetic
  940. return (n << 1) ^ (n >> 31);
  941. }
  942. /**
  943. * Encode a ZigZag-encoded 64-bit value. ZigZag encodes signed integers
  944. * into values that can be efficiently encoded with varint. (Otherwise,
  945. * negative values must be sign-extended to 64 bits to be varint encoded,
  946. * thus always taking 10 bytes on the wire.)
  947. *
  948. * @param n A signed 64-bit integer.
  949. * @return An unsigned 64-bit integer, stored in a signed int because
  950. * Java has no explicit unsigned support.
  951. */
  952. public static long encodeZigZag64(final long n) {
  953. // Note: the right-shift must be arithmetic
  954. return (n << 1) ^ (n >> 63);
  955. }
  956. }