CodedOutputStream.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  1. #region Copyright notice and license
  2. // Protocol Buffers - Google's data interchange format
  3. // Copyright 2008 Google Inc. All rights reserved.
  4. // https://developers.google.com/protocol-buffers/
  5. //
  6. // Redistribution and use in source and binary forms, with or without
  7. // modification, are permitted provided that the following conditions are
  8. // met:
  9. //
  10. // * Redistributions of source code must retain the above copyright
  11. // notice, this list of conditions and the following disclaimer.
  12. // * Redistributions in binary form must reproduce the above
  13. // copyright notice, this list of conditions and the following disclaimer
  14. // in the documentation and/or other materials provided with the
  15. // distribution.
  16. // * Neither the name of Google Inc. nor the names of its
  17. // contributors may be used to endorse or promote products derived from
  18. // this software without specific prior written permission.
  19. //
  20. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. #endregion
  32. using Google.Protobuf.Collections;
  33. using System;
  34. using System.IO;
  35. using System.Text;
  36. namespace Google.Protobuf
  37. {
  38. /// <summary>
  39. /// Encodes and writes protocol message fields.
  40. /// </summary>
  41. /// <remarks>
  42. /// <para>
  43. /// This class is generally used by generated code to write appropriate
  44. /// primitives to the stream. It effectively encapsulates the lowest
  45. /// levels of protocol buffer format. Unlike some other implementations,
  46. /// this does not include combined "write tag and value" methods. Generated
  47. /// code knows the exact byte representations of the tags they're going to write,
  48. /// so there's no need to re-encode them each time. Manually-written code calling
  49. /// this class should just call one of the <c>WriteTag</c> overloads before each value.
  50. /// </para>
  51. /// <para>
  52. /// Repeated fields and map fields are not handled by this class; use <c>RepeatedField&lt;T&gt;</c>
  53. /// and <c>MapField&lt;TKey, TValue&gt;</c> to serialize such fields.
  54. /// </para>
  55. /// </remarks>
  56. public sealed partial class CodedOutputStream : IDisposable
  57. {
  58. // "Local" copy of Encoding.UTF8, for efficiency. (Yes, it makes a difference.)
  59. internal static readonly Encoding Utf8Encoding = Encoding.UTF8;
  60. /// <summary>
  61. /// The buffer size used by CreateInstance(Stream).
  62. /// </summary>
  63. public static readonly int DefaultBufferSize = 4096;
  64. private readonly bool leaveOpen;
  65. private readonly byte[] buffer;
  66. private readonly int limit;
  67. private int position;
  68. private readonly Stream output;
  69. #region Construction
  70. /// <summary>
  71. /// Creates a new CodedOutputStream that writes directly to the given
  72. /// byte array. If more bytes are written than fit in the array,
  73. /// OutOfSpaceException will be thrown.
  74. /// </summary>
  75. public CodedOutputStream(byte[] flatArray) : this(flatArray, 0, flatArray.Length)
  76. {
  77. }
  78. /// <summary>
  79. /// Creates a new CodedOutputStream that writes directly to the given
  80. /// byte array slice. If more bytes are written than fit in the array,
  81. /// OutOfSpaceException will be thrown.
  82. /// </summary>
  83. private CodedOutputStream(byte[] buffer, int offset, int length)
  84. {
  85. this.output = null;
  86. this.buffer = buffer;
  87. this.position = offset;
  88. this.limit = offset + length;
  89. leaveOpen = true; // Simple way of avoiding trying to dispose of a null reference
  90. }
  91. private CodedOutputStream(Stream output, byte[] buffer, bool leaveOpen)
  92. {
  93. this.output = ProtoPreconditions.CheckNotNull(output, "output");
  94. this.buffer = buffer;
  95. this.position = 0;
  96. this.limit = buffer.Length;
  97. this.leaveOpen = leaveOpen;
  98. }
  99. /// <summary>
  100. /// Creates a new <see cref="CodedOutputStream" /> which write to the given stream, and disposes of that
  101. /// stream when the returned <c>CodedOutputStream</c> is disposed.
  102. /// </summary>
  103. /// <param name="output">The stream to write to. It will be disposed when the returned <c>CodedOutputStream is disposed.</c></param>
  104. public CodedOutputStream(Stream output) : this(output, DefaultBufferSize, false)
  105. {
  106. }
  107. /// <summary>
  108. /// Creates a new CodedOutputStream which write to the given stream and uses
  109. /// the specified buffer size.
  110. /// </summary>
  111. /// <param name="output">The stream to write to. It will be disposed when the returned <c>CodedOutputStream is disposed.</c></param>
  112. /// <param name="bufferSize">The size of buffer to use internally.</param>
  113. public CodedOutputStream(Stream output, int bufferSize) : this(output, new byte[bufferSize], false)
  114. {
  115. }
  116. /// <summary>
  117. /// Creates a new CodedOutputStream which write to the given stream.
  118. /// </summary>
  119. /// <param name="output">The stream to write to.</param>
  120. /// <param name="leaveOpen">If <c>true</c>, <paramref name="output"/> is left open when the returned <c>CodedOutputStream</c> is disposed;
  121. /// if <c>false</c>, the provided stream is disposed as well.</param>
  122. public CodedOutputStream(Stream output, bool leaveOpen) : this(output, DefaultBufferSize, leaveOpen)
  123. {
  124. }
  125. /// <summary>
  126. /// Creates a new CodedOutputStream which write to the given stream and uses
  127. /// the specified buffer size.
  128. /// </summary>
  129. /// <param name="output">The stream to write to.</param>
  130. /// <param name="bufferSize">The size of buffer to use internally.</param>
  131. /// <param name="leaveOpen">If <c>true</c>, <paramref name="output"/> is left open when the returned <c>CodedOutputStream</c> is disposed;
  132. /// if <c>false</c>, the provided stream is disposed as well.</param>
  133. public CodedOutputStream(Stream output, int bufferSize, bool leaveOpen) : this(output, new byte[bufferSize], leaveOpen)
  134. {
  135. }
  136. #endregion
  137. /// <summary>
  138. /// Returns the current position in the stream, or the position in the output buffer
  139. /// </summary>
  140. public long Position
  141. {
  142. get
  143. {
  144. if (output != null)
  145. {
  146. return output.Position + position;
  147. }
  148. return position;
  149. }
  150. }
  151. #region Writing of values (not including tags)
  152. /// <summary>
  153. /// Writes a double field value, without a tag, to the stream.
  154. /// </summary>
  155. /// <param name="value">The value to write</param>
  156. public void WriteDouble(double value)
  157. {
  158. WriteRawLittleEndian64((ulong)BitConverter.DoubleToInt64Bits(value));
  159. }
  160. /// <summary>
  161. /// Writes a float field value, without a tag, to the stream.
  162. /// </summary>
  163. /// <param name="value">The value to write</param>
  164. public void WriteFloat(float value)
  165. {
  166. byte[] rawBytes = BitConverter.GetBytes(value);
  167. if (!BitConverter.IsLittleEndian)
  168. {
  169. ByteArray.Reverse(rawBytes);
  170. }
  171. if (limit - position >= 4)
  172. {
  173. buffer[position++] = rawBytes[0];
  174. buffer[position++] = rawBytes[1];
  175. buffer[position++] = rawBytes[2];
  176. buffer[position++] = rawBytes[3];
  177. }
  178. else
  179. {
  180. WriteRawBytes(rawBytes, 0, 4);
  181. }
  182. }
  183. /// <summary>
  184. /// Writes a uint64 field value, without a tag, to the stream.
  185. /// </summary>
  186. /// <param name="value">The value to write</param>
  187. public void WriteUInt64(ulong value)
  188. {
  189. WriteRawVarint64(value);
  190. }
  191. /// <summary>
  192. /// Writes an int64 field value, without a tag, to the stream.
  193. /// </summary>
  194. /// <param name="value">The value to write</param>
  195. public void WriteInt64(long value)
  196. {
  197. WriteRawVarint64((ulong) value);
  198. }
  199. /// <summary>
  200. /// Writes an int32 field value, without a tag, to the stream.
  201. /// </summary>
  202. /// <param name="value">The value to write</param>
  203. public void WriteInt32(int value)
  204. {
  205. if (value >= 0)
  206. {
  207. WriteRawVarint32((uint) value);
  208. }
  209. else
  210. {
  211. // Must sign-extend.
  212. WriteRawVarint64((ulong) value);
  213. }
  214. }
  215. /// <summary>
  216. /// Writes a fixed64 field value, without a tag, to the stream.
  217. /// </summary>
  218. /// <param name="value">The value to write</param>
  219. public void WriteFixed64(ulong value)
  220. {
  221. WriteRawLittleEndian64(value);
  222. }
  223. /// <summary>
  224. /// Writes a fixed32 field value, without a tag, to the stream.
  225. /// </summary>
  226. /// <param name="value">The value to write</param>
  227. public void WriteFixed32(uint value)
  228. {
  229. WriteRawLittleEndian32(value);
  230. }
  231. /// <summary>
  232. /// Writes a bool field value, without a tag, to the stream.
  233. /// </summary>
  234. /// <param name="value">The value to write</param>
  235. public void WriteBool(bool value)
  236. {
  237. WriteRawByte(value ? (byte) 1 : (byte) 0);
  238. }
  239. /// <summary>
  240. /// Writes a string field value, without a tag, to the stream.
  241. /// The data is length-prefixed.
  242. /// </summary>
  243. /// <param name="value">The value to write</param>
  244. public void WriteString(string value)
  245. {
  246. // Optimise the case where we have enough space to write
  247. // the string directly to the buffer, which should be common.
  248. int length = Utf8Encoding.GetByteCount(value);
  249. WriteLength(length);
  250. if (limit - position >= length)
  251. {
  252. if (length == value.Length) // Must be all ASCII...
  253. {
  254. for (int i = 0; i < length; i++)
  255. {
  256. buffer[position + i] = (byte)value[i];
  257. }
  258. }
  259. else
  260. {
  261. Utf8Encoding.GetBytes(value, 0, value.Length, buffer, position);
  262. }
  263. position += length;
  264. }
  265. else
  266. {
  267. byte[] bytes = Utf8Encoding.GetBytes(value);
  268. WriteRawBytes(bytes);
  269. }
  270. }
  271. /// <summary>
  272. /// Writes a message, without a tag, to the stream.
  273. /// The data is length-prefixed.
  274. /// </summary>
  275. /// <param name="value">The value to write</param>
  276. public void WriteMessage(IMessage value)
  277. {
  278. WriteLength(value.CalculateSize());
  279. value.WriteTo(this);
  280. }
  281. /// <summary>
  282. /// Write a byte string, without a tag, to the stream.
  283. /// The data is length-prefixed.
  284. /// </summary>
  285. /// <param name="value">The value to write</param>
  286. public void WriteBytes(ByteString value)
  287. {
  288. WriteLength(value.Length);
  289. value.WriteRawBytesTo(this);
  290. }
  291. /// <summary>
  292. /// Writes a uint32 value, without a tag, to the stream.
  293. /// </summary>
  294. /// <param name="value">The value to write</param>
  295. public void WriteUInt32(uint value)
  296. {
  297. WriteRawVarint32(value);
  298. }
  299. /// <summary>
  300. /// Writes an enum value, without a tag, to the stream.
  301. /// </summary>
  302. /// <param name="value">The value to write</param>
  303. public void WriteEnum(int value)
  304. {
  305. WriteInt32(value);
  306. }
  307. /// <summary>
  308. /// Writes an sfixed32 value, without a tag, to the stream.
  309. /// </summary>
  310. /// <param name="value">The value to write.</param>
  311. public void WriteSFixed32(int value)
  312. {
  313. WriteRawLittleEndian32((uint) value);
  314. }
  315. /// <summary>
  316. /// Writes an sfixed64 value, without a tag, to the stream.
  317. /// </summary>
  318. /// <param name="value">The value to write</param>
  319. public void WriteSFixed64(long value)
  320. {
  321. WriteRawLittleEndian64((ulong) value);
  322. }
  323. /// <summary>
  324. /// Writes an sint32 value, without a tag, to the stream.
  325. /// </summary>
  326. /// <param name="value">The value to write</param>
  327. public void WriteSInt32(int value)
  328. {
  329. WriteRawVarint32(EncodeZigZag32(value));
  330. }
  331. /// <summary>
  332. /// Writes an sint64 value, without a tag, to the stream.
  333. /// </summary>
  334. /// <param name="value">The value to write</param>
  335. public void WriteSInt64(long value)
  336. {
  337. WriteRawVarint64(EncodeZigZag64(value));
  338. }
  339. /// <summary>
  340. /// Writes a length (in bytes) for length-delimited data.
  341. /// </summary>
  342. /// <remarks>
  343. /// This method simply writes a rawint, but exists for clarity in calling code.
  344. /// </remarks>
  345. /// <param name="length">Length value, in bytes.</param>
  346. public void WriteLength(int length)
  347. {
  348. WriteRawVarint32((uint) length);
  349. }
  350. #endregion
  351. #region Raw tag writing
  352. /// <summary>
  353. /// Encodes and writes a tag.
  354. /// </summary>
  355. /// <param name="fieldNumber">The number of the field to write the tag for</param>
  356. /// <param name="type">The wire format type of the tag to write</param>
  357. public void WriteTag(int fieldNumber, WireFormat.WireType type)
  358. {
  359. WriteRawVarint32(WireFormat.MakeTag(fieldNumber, type));
  360. }
  361. /// <summary>
  362. /// Writes an already-encoded tag.
  363. /// </summary>
  364. /// <param name="tag">The encoded tag</param>
  365. public void WriteTag(uint tag)
  366. {
  367. WriteRawVarint32(tag);
  368. }
  369. /// <summary>
  370. /// Writes the given single-byte tag directly to the stream.
  371. /// </summary>
  372. /// <param name="b1">The encoded tag</param>
  373. public void WriteRawTag(byte b1)
  374. {
  375. WriteRawByte(b1);
  376. }
  377. /// <summary>
  378. /// Writes the given two-byte tag directly to the stream.
  379. /// </summary>
  380. /// <param name="b1">The first byte of the encoded tag</param>
  381. /// <param name="b2">The second byte of the encoded tag</param>
  382. public void WriteRawTag(byte b1, byte b2)
  383. {
  384. WriteRawByte(b1);
  385. WriteRawByte(b2);
  386. }
  387. /// <summary>
  388. /// Writes the given three-byte tag directly to the stream.
  389. /// </summary>
  390. /// <param name="b1">The first byte of the encoded tag</param>
  391. /// <param name="b2">The second byte of the encoded tag</param>
  392. /// <param name="b3">The third byte of the encoded tag</param>
  393. public void WriteRawTag(byte b1, byte b2, byte b3)
  394. {
  395. WriteRawByte(b1);
  396. WriteRawByte(b2);
  397. WriteRawByte(b3);
  398. }
  399. /// <summary>
  400. /// Writes the given four-byte tag directly to the stream.
  401. /// </summary>
  402. /// <param name="b1">The first byte of the encoded tag</param>
  403. /// <param name="b2">The second byte of the encoded tag</param>
  404. /// <param name="b3">The third byte of the encoded tag</param>
  405. /// <param name="b4">The fourth byte of the encoded tag</param>
  406. public void WriteRawTag(byte b1, byte b2, byte b3, byte b4)
  407. {
  408. WriteRawByte(b1);
  409. WriteRawByte(b2);
  410. WriteRawByte(b3);
  411. WriteRawByte(b4);
  412. }
  413. /// <summary>
  414. /// Writes the given five-byte tag directly to the stream.
  415. /// </summary>
  416. /// <param name="b1">The first byte of the encoded tag</param>
  417. /// <param name="b2">The second byte of the encoded tag</param>
  418. /// <param name="b3">The third byte of the encoded tag</param>
  419. /// <param name="b4">The fourth byte of the encoded tag</param>
  420. /// <param name="b5">The fifth byte of the encoded tag</param>
  421. public void WriteRawTag(byte b1, byte b2, byte b3, byte b4, byte b5)
  422. {
  423. WriteRawByte(b1);
  424. WriteRawByte(b2);
  425. WriteRawByte(b3);
  426. WriteRawByte(b4);
  427. WriteRawByte(b5);
  428. }
  429. #endregion
  430. #region Underlying writing primitives
  431. /// <summary>
  432. /// Writes a 32 bit value as a varint. The fast route is taken when
  433. /// there's enough buffer space left to whizz through without checking
  434. /// for each byte; otherwise, we resort to calling WriteRawByte each time.
  435. /// </summary>
  436. internal void WriteRawVarint32(uint value)
  437. {
  438. // Optimize for the common case of a single byte value
  439. if (value < 128 && position < limit)
  440. {
  441. buffer[position++] = (byte)value;
  442. return;
  443. }
  444. while (value > 127 && position < limit)
  445. {
  446. buffer[position++] = (byte) ((value & 0x7F) | 0x80);
  447. value >>= 7;
  448. }
  449. while (value > 127)
  450. {
  451. WriteRawByte((byte) ((value & 0x7F) | 0x80));
  452. value >>= 7;
  453. }
  454. if (position < limit)
  455. {
  456. buffer[position++] = (byte) value;
  457. }
  458. else
  459. {
  460. WriteRawByte((byte) value);
  461. }
  462. }
  463. internal void WriteRawVarint64(ulong value)
  464. {
  465. while (value > 127 && position < limit)
  466. {
  467. buffer[position++] = (byte) ((value & 0x7F) | 0x80);
  468. value >>= 7;
  469. }
  470. while (value > 127)
  471. {
  472. WriteRawByte((byte) ((value & 0x7F) | 0x80));
  473. value >>= 7;
  474. }
  475. if (position < limit)
  476. {
  477. buffer[position++] = (byte) value;
  478. }
  479. else
  480. {
  481. WriteRawByte((byte) value);
  482. }
  483. }
  484. internal void WriteRawLittleEndian32(uint value)
  485. {
  486. if (position + 4 > limit)
  487. {
  488. WriteRawByte((byte) value);
  489. WriteRawByte((byte) (value >> 8));
  490. WriteRawByte((byte) (value >> 16));
  491. WriteRawByte((byte) (value >> 24));
  492. }
  493. else
  494. {
  495. buffer[position++] = ((byte) value);
  496. buffer[position++] = ((byte) (value >> 8));
  497. buffer[position++] = ((byte) (value >> 16));
  498. buffer[position++] = ((byte) (value >> 24));
  499. }
  500. }
  501. internal void WriteRawLittleEndian64(ulong value)
  502. {
  503. if (position + 8 > limit)
  504. {
  505. WriteRawByte((byte) value);
  506. WriteRawByte((byte) (value >> 8));
  507. WriteRawByte((byte) (value >> 16));
  508. WriteRawByte((byte) (value >> 24));
  509. WriteRawByte((byte) (value >> 32));
  510. WriteRawByte((byte) (value >> 40));
  511. WriteRawByte((byte) (value >> 48));
  512. WriteRawByte((byte) (value >> 56));
  513. }
  514. else
  515. {
  516. buffer[position++] = ((byte) value);
  517. buffer[position++] = ((byte) (value >> 8));
  518. buffer[position++] = ((byte) (value >> 16));
  519. buffer[position++] = ((byte) (value >> 24));
  520. buffer[position++] = ((byte) (value >> 32));
  521. buffer[position++] = ((byte) (value >> 40));
  522. buffer[position++] = ((byte) (value >> 48));
  523. buffer[position++] = ((byte) (value >> 56));
  524. }
  525. }
  526. internal void WriteRawByte(byte value)
  527. {
  528. if (position == limit)
  529. {
  530. RefreshBuffer();
  531. }
  532. buffer[position++] = value;
  533. }
  534. internal void WriteRawByte(uint value)
  535. {
  536. WriteRawByte((byte) value);
  537. }
  538. /// <summary>
  539. /// Writes out an array of bytes.
  540. /// </summary>
  541. internal void WriteRawBytes(byte[] value)
  542. {
  543. WriteRawBytes(value, 0, value.Length);
  544. }
  545. /// <summary>
  546. /// Writes out part of an array of bytes.
  547. /// </summary>
  548. internal void WriteRawBytes(byte[] value, int offset, int length)
  549. {
  550. if (limit - position >= length)
  551. {
  552. ByteArray.Copy(value, offset, buffer, position, length);
  553. // We have room in the current buffer.
  554. position += length;
  555. }
  556. else
  557. {
  558. // Write extends past current buffer. Fill the rest of this buffer and
  559. // flush.
  560. int bytesWritten = limit - position;
  561. ByteArray.Copy(value, offset, buffer, position, bytesWritten);
  562. offset += bytesWritten;
  563. length -= bytesWritten;
  564. position = limit;
  565. RefreshBuffer();
  566. // Now deal with the rest.
  567. // Since we have an output stream, this is our buffer
  568. // and buffer offset == 0
  569. if (length <= limit)
  570. {
  571. // Fits in new buffer.
  572. ByteArray.Copy(value, offset, buffer, 0, length);
  573. position = length;
  574. }
  575. else
  576. {
  577. // Write is very big. Let's do it all at once.
  578. output.Write(value, offset, length);
  579. }
  580. }
  581. }
  582. #endregion
  583. /// <summary>
  584. /// Encode a 32-bit value with ZigZag encoding.
  585. /// </summary>
  586. /// <remarks>
  587. /// ZigZag encodes signed integers into values that can be efficiently
  588. /// encoded with varint. (Otherwise, negative values must be
  589. /// sign-extended to 64 bits to be varint encoded, thus always taking
  590. /// 10 bytes on the wire.)
  591. /// </remarks>
  592. internal static uint EncodeZigZag32(int n)
  593. {
  594. // Note: the right-shift must be arithmetic
  595. return (uint) ((n << 1) ^ (n >> 31));
  596. }
  597. /// <summary>
  598. /// Encode a 64-bit value with ZigZag encoding.
  599. /// </summary>
  600. /// <remarks>
  601. /// ZigZag encodes signed integers into values that can be efficiently
  602. /// encoded with varint. (Otherwise, negative values must be
  603. /// sign-extended to 64 bits to be varint encoded, thus always taking
  604. /// 10 bytes on the wire.)
  605. /// </remarks>
  606. internal static ulong EncodeZigZag64(long n)
  607. {
  608. return (ulong) ((n << 1) ^ (n >> 63));
  609. }
  610. private void RefreshBuffer()
  611. {
  612. if (output == null)
  613. {
  614. // We're writing to a single buffer.
  615. throw new OutOfSpaceException();
  616. }
  617. // Since we have an output stream, this is our buffer
  618. // and buffer offset == 0
  619. output.Write(buffer, 0, position);
  620. position = 0;
  621. }
  622. /// <summary>
  623. /// Indicates that a CodedOutputStream wrapping a flat byte array
  624. /// ran out of space.
  625. /// </summary>
  626. public sealed class OutOfSpaceException : IOException
  627. {
  628. internal OutOfSpaceException()
  629. : base("CodedOutputStream was writing to a flat byte array and ran out of space.")
  630. {
  631. }
  632. }
  633. /// <summary>
  634. /// Flushes any buffered data and optionally closes the underlying stream, if any.
  635. /// </summary>
  636. /// <remarks>
  637. /// <para>
  638. /// By default, any underlying stream is closed by this method. To configure this behaviour,
  639. /// use a constructor overload with a <c>leaveOpen</c> parameter. If this instance does not
  640. /// have an underlying stream, this method does nothing.
  641. /// </para>
  642. /// <para>
  643. /// For the sake of efficiency, calling this method does not prevent future write calls - but
  644. /// if a later write ends up writing to a stream which has been disposed, that is likely to
  645. /// fail. It is recommend that you not call any other methods after this.
  646. /// </para>
  647. /// </remarks>
  648. public void Dispose()
  649. {
  650. Flush();
  651. if (!leaveOpen)
  652. {
  653. output.Dispose();
  654. }
  655. }
  656. /// <summary>
  657. /// Flushes any buffered data to the underlying stream (if there is one).
  658. /// </summary>
  659. public void Flush()
  660. {
  661. if (output != null)
  662. {
  663. RefreshBuffer();
  664. }
  665. }
  666. /// <summary>
  667. /// Verifies that SpaceLeft returns zero. It's common to create a byte array
  668. /// that is exactly big enough to hold a message, then write to it with
  669. /// a CodedOutputStream. Calling CheckNoSpaceLeft after writing verifies that
  670. /// the message was actually as big as expected, which can help bugs.
  671. /// </summary>
  672. public void CheckNoSpaceLeft()
  673. {
  674. if (SpaceLeft != 0)
  675. {
  676. throw new InvalidOperationException("Did not write as much data as expected.");
  677. }
  678. }
  679. /// <summary>
  680. /// If writing to a flat array, returns the space left in the array. Otherwise,
  681. /// throws an InvalidOperationException.
  682. /// </summary>
  683. public int SpaceLeft
  684. {
  685. get
  686. {
  687. if (output == null)
  688. {
  689. return limit - position;
  690. }
  691. else
  692. {
  693. throw new InvalidOperationException(
  694. "SpaceLeft can only be called on CodedOutputStreams that are " +
  695. "writing to a flat array.");
  696. }
  697. }
  698. }
  699. }
  700. }