CodedOutputStream.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  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, nameof(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. /// Writes a group, without a tag, to the stream.
  283. /// </summary>
  284. /// <param name="value">The value to write</param>
  285. public void WriteGroup(IMessage value)
  286. {
  287. value.WriteTo(this);
  288. }
  289. /// <summary>
  290. /// Write a byte string, without a tag, to the stream.
  291. /// The data is length-prefixed.
  292. /// </summary>
  293. /// <param name="value">The value to write</param>
  294. public void WriteBytes(ByteString value)
  295. {
  296. WriteLength(value.Length);
  297. value.WriteRawBytesTo(this);
  298. }
  299. /// <summary>
  300. /// Writes a uint32 value, without a tag, to the stream.
  301. /// </summary>
  302. /// <param name="value">The value to write</param>
  303. public void WriteUInt32(uint value)
  304. {
  305. WriteRawVarint32(value);
  306. }
  307. /// <summary>
  308. /// Writes an enum value, without a tag, to the stream.
  309. /// </summary>
  310. /// <param name="value">The value to write</param>
  311. public void WriteEnum(int value)
  312. {
  313. WriteInt32(value);
  314. }
  315. /// <summary>
  316. /// Writes an sfixed32 value, without a tag, to the stream.
  317. /// </summary>
  318. /// <param name="value">The value to write.</param>
  319. public void WriteSFixed32(int value)
  320. {
  321. WriteRawLittleEndian32((uint) value);
  322. }
  323. /// <summary>
  324. /// Writes an sfixed64 value, without a tag, to the stream.
  325. /// </summary>
  326. /// <param name="value">The value to write</param>
  327. public void WriteSFixed64(long value)
  328. {
  329. WriteRawLittleEndian64((ulong) value);
  330. }
  331. /// <summary>
  332. /// Writes an sint32 value, without a tag, to the stream.
  333. /// </summary>
  334. /// <param name="value">The value to write</param>
  335. public void WriteSInt32(int value)
  336. {
  337. WriteRawVarint32(EncodeZigZag32(value));
  338. }
  339. /// <summary>
  340. /// Writes an sint64 value, without a tag, to the stream.
  341. /// </summary>
  342. /// <param name="value">The value to write</param>
  343. public void WriteSInt64(long value)
  344. {
  345. WriteRawVarint64(EncodeZigZag64(value));
  346. }
  347. /// <summary>
  348. /// Writes a length (in bytes) for length-delimited data.
  349. /// </summary>
  350. /// <remarks>
  351. /// This method simply writes a rawint, but exists for clarity in calling code.
  352. /// </remarks>
  353. /// <param name="length">Length value, in bytes.</param>
  354. public void WriteLength(int length)
  355. {
  356. WriteRawVarint32((uint) length);
  357. }
  358. #endregion
  359. #region Raw tag writing
  360. /// <summary>
  361. /// Encodes and writes a tag.
  362. /// </summary>
  363. /// <param name="fieldNumber">The number of the field to write the tag for</param>
  364. /// <param name="type">The wire format type of the tag to write</param>
  365. public void WriteTag(int fieldNumber, WireFormat.WireType type)
  366. {
  367. WriteRawVarint32(WireFormat.MakeTag(fieldNumber, type));
  368. }
  369. /// <summary>
  370. /// Writes an already-encoded tag.
  371. /// </summary>
  372. /// <param name="tag">The encoded tag</param>
  373. public void WriteTag(uint tag)
  374. {
  375. WriteRawVarint32(tag);
  376. }
  377. /// <summary>
  378. /// Writes the given single-byte tag directly to the stream.
  379. /// </summary>
  380. /// <param name="b1">The encoded tag</param>
  381. public void WriteRawTag(byte b1)
  382. {
  383. WriteRawByte(b1);
  384. }
  385. /// <summary>
  386. /// Writes the given two-byte tag directly to the stream.
  387. /// </summary>
  388. /// <param name="b1">The first byte of the encoded tag</param>
  389. /// <param name="b2">The second byte of the encoded tag</param>
  390. public void WriteRawTag(byte b1, byte b2)
  391. {
  392. WriteRawByte(b1);
  393. WriteRawByte(b2);
  394. }
  395. /// <summary>
  396. /// Writes the given three-byte tag directly to the stream.
  397. /// </summary>
  398. /// <param name="b1">The first byte of the encoded tag</param>
  399. /// <param name="b2">The second byte of the encoded tag</param>
  400. /// <param name="b3">The third byte of the encoded tag</param>
  401. public void WriteRawTag(byte b1, byte b2, byte b3)
  402. {
  403. WriteRawByte(b1);
  404. WriteRawByte(b2);
  405. WriteRawByte(b3);
  406. }
  407. /// <summary>
  408. /// Writes the given four-byte tag directly to the stream.
  409. /// </summary>
  410. /// <param name="b1">The first byte of the encoded tag</param>
  411. /// <param name="b2">The second byte of the encoded tag</param>
  412. /// <param name="b3">The third byte of the encoded tag</param>
  413. /// <param name="b4">The fourth byte of the encoded tag</param>
  414. public void WriteRawTag(byte b1, byte b2, byte b3, byte b4)
  415. {
  416. WriteRawByte(b1);
  417. WriteRawByte(b2);
  418. WriteRawByte(b3);
  419. WriteRawByte(b4);
  420. }
  421. /// <summary>
  422. /// Writes the given five-byte tag directly to the stream.
  423. /// </summary>
  424. /// <param name="b1">The first byte of the encoded tag</param>
  425. /// <param name="b2">The second byte of the encoded tag</param>
  426. /// <param name="b3">The third byte of the encoded tag</param>
  427. /// <param name="b4">The fourth byte of the encoded tag</param>
  428. /// <param name="b5">The fifth byte of the encoded tag</param>
  429. public void WriteRawTag(byte b1, byte b2, byte b3, byte b4, byte b5)
  430. {
  431. WriteRawByte(b1);
  432. WriteRawByte(b2);
  433. WriteRawByte(b3);
  434. WriteRawByte(b4);
  435. WriteRawByte(b5);
  436. }
  437. #endregion
  438. #region Underlying writing primitives
  439. /// <summary>
  440. /// Writes a 32 bit value as a varint. The fast route is taken when
  441. /// there's enough buffer space left to whizz through without checking
  442. /// for each byte; otherwise, we resort to calling WriteRawByte each time.
  443. /// </summary>
  444. internal void WriteRawVarint32(uint value)
  445. {
  446. // Optimize for the common case of a single byte value
  447. if (value < 128 && position < limit)
  448. {
  449. buffer[position++] = (byte)value;
  450. return;
  451. }
  452. while (value > 127 && position < limit)
  453. {
  454. buffer[position++] = (byte) ((value & 0x7F) | 0x80);
  455. value >>= 7;
  456. }
  457. while (value > 127)
  458. {
  459. WriteRawByte((byte) ((value & 0x7F) | 0x80));
  460. value >>= 7;
  461. }
  462. if (position < limit)
  463. {
  464. buffer[position++] = (byte) value;
  465. }
  466. else
  467. {
  468. WriteRawByte((byte) value);
  469. }
  470. }
  471. internal void WriteRawVarint64(ulong value)
  472. {
  473. while (value > 127 && position < limit)
  474. {
  475. buffer[position++] = (byte) ((value & 0x7F) | 0x80);
  476. value >>= 7;
  477. }
  478. while (value > 127)
  479. {
  480. WriteRawByte((byte) ((value & 0x7F) | 0x80));
  481. value >>= 7;
  482. }
  483. if (position < limit)
  484. {
  485. buffer[position++] = (byte) value;
  486. }
  487. else
  488. {
  489. WriteRawByte((byte) value);
  490. }
  491. }
  492. internal void WriteRawLittleEndian32(uint value)
  493. {
  494. if (position + 4 > limit)
  495. {
  496. WriteRawByte((byte) value);
  497. WriteRawByte((byte) (value >> 8));
  498. WriteRawByte((byte) (value >> 16));
  499. WriteRawByte((byte) (value >> 24));
  500. }
  501. else
  502. {
  503. buffer[position++] = ((byte) value);
  504. buffer[position++] = ((byte) (value >> 8));
  505. buffer[position++] = ((byte) (value >> 16));
  506. buffer[position++] = ((byte) (value >> 24));
  507. }
  508. }
  509. internal void WriteRawLittleEndian64(ulong value)
  510. {
  511. if (position + 8 > limit)
  512. {
  513. WriteRawByte((byte) value);
  514. WriteRawByte((byte) (value >> 8));
  515. WriteRawByte((byte) (value >> 16));
  516. WriteRawByte((byte) (value >> 24));
  517. WriteRawByte((byte) (value >> 32));
  518. WriteRawByte((byte) (value >> 40));
  519. WriteRawByte((byte) (value >> 48));
  520. WriteRawByte((byte) (value >> 56));
  521. }
  522. else
  523. {
  524. buffer[position++] = ((byte) value);
  525. buffer[position++] = ((byte) (value >> 8));
  526. buffer[position++] = ((byte) (value >> 16));
  527. buffer[position++] = ((byte) (value >> 24));
  528. buffer[position++] = ((byte) (value >> 32));
  529. buffer[position++] = ((byte) (value >> 40));
  530. buffer[position++] = ((byte) (value >> 48));
  531. buffer[position++] = ((byte) (value >> 56));
  532. }
  533. }
  534. internal void WriteRawByte(byte value)
  535. {
  536. if (position == limit)
  537. {
  538. RefreshBuffer();
  539. }
  540. buffer[position++] = value;
  541. }
  542. internal void WriteRawByte(uint value)
  543. {
  544. WriteRawByte((byte) value);
  545. }
  546. /// <summary>
  547. /// Writes out an array of bytes.
  548. /// </summary>
  549. internal void WriteRawBytes(byte[] value)
  550. {
  551. WriteRawBytes(value, 0, value.Length);
  552. }
  553. /// <summary>
  554. /// Writes out part of an array of bytes.
  555. /// </summary>
  556. internal void WriteRawBytes(byte[] value, int offset, int length)
  557. {
  558. if (limit - position >= length)
  559. {
  560. ByteArray.Copy(value, offset, buffer, position, length);
  561. // We have room in the current buffer.
  562. position += length;
  563. }
  564. else
  565. {
  566. // Write extends past current buffer. Fill the rest of this buffer and
  567. // flush.
  568. int bytesWritten = limit - position;
  569. ByteArray.Copy(value, offset, buffer, position, bytesWritten);
  570. offset += bytesWritten;
  571. length -= bytesWritten;
  572. position = limit;
  573. RefreshBuffer();
  574. // Now deal with the rest.
  575. // Since we have an output stream, this is our buffer
  576. // and buffer offset == 0
  577. if (length <= limit)
  578. {
  579. // Fits in new buffer.
  580. ByteArray.Copy(value, offset, buffer, 0, length);
  581. position = length;
  582. }
  583. else
  584. {
  585. // Write is very big. Let's do it all at once.
  586. output.Write(value, offset, length);
  587. }
  588. }
  589. }
  590. #endregion
  591. /// <summary>
  592. /// Encode a 32-bit value with ZigZag encoding.
  593. /// </summary>
  594. /// <remarks>
  595. /// ZigZag encodes signed integers into values that can be efficiently
  596. /// encoded with varint. (Otherwise, negative values must be
  597. /// sign-extended to 64 bits to be varint encoded, thus always taking
  598. /// 10 bytes on the wire.)
  599. /// </remarks>
  600. internal static uint EncodeZigZag32(int n)
  601. {
  602. // Note: the right-shift must be arithmetic
  603. return (uint) ((n << 1) ^ (n >> 31));
  604. }
  605. /// <summary>
  606. /// Encode a 64-bit value with ZigZag encoding.
  607. /// </summary>
  608. /// <remarks>
  609. /// ZigZag encodes signed integers into values that can be efficiently
  610. /// encoded with varint. (Otherwise, negative values must be
  611. /// sign-extended to 64 bits to be varint encoded, thus always taking
  612. /// 10 bytes on the wire.)
  613. /// </remarks>
  614. internal static ulong EncodeZigZag64(long n)
  615. {
  616. return (ulong) ((n << 1) ^ (n >> 63));
  617. }
  618. private void RefreshBuffer()
  619. {
  620. if (output == null)
  621. {
  622. // We're writing to a single buffer.
  623. throw new OutOfSpaceException();
  624. }
  625. // Since we have an output stream, this is our buffer
  626. // and buffer offset == 0
  627. output.Write(buffer, 0, position);
  628. position = 0;
  629. }
  630. /// <summary>
  631. /// Indicates that a CodedOutputStream wrapping a flat byte array
  632. /// ran out of space.
  633. /// </summary>
  634. public sealed class OutOfSpaceException : IOException
  635. {
  636. internal OutOfSpaceException()
  637. : base("CodedOutputStream was writing to a flat byte array and ran out of space.")
  638. {
  639. }
  640. }
  641. /// <summary>
  642. /// Flushes any buffered data and optionally closes the underlying stream, if any.
  643. /// </summary>
  644. /// <remarks>
  645. /// <para>
  646. /// By default, any underlying stream is closed by this method. To configure this behaviour,
  647. /// use a constructor overload with a <c>leaveOpen</c> parameter. If this instance does not
  648. /// have an underlying stream, this method does nothing.
  649. /// </para>
  650. /// <para>
  651. /// For the sake of efficiency, calling this method does not prevent future write calls - but
  652. /// if a later write ends up writing to a stream which has been disposed, that is likely to
  653. /// fail. It is recommend that you not call any other methods after this.
  654. /// </para>
  655. /// </remarks>
  656. public void Dispose()
  657. {
  658. Flush();
  659. if (!leaveOpen)
  660. {
  661. output.Dispose();
  662. }
  663. }
  664. /// <summary>
  665. /// Flushes any buffered data to the underlying stream (if there is one).
  666. /// </summary>
  667. public void Flush()
  668. {
  669. if (output != null)
  670. {
  671. RefreshBuffer();
  672. }
  673. }
  674. /// <summary>
  675. /// Verifies that SpaceLeft returns zero. It's common to create a byte array
  676. /// that is exactly big enough to hold a message, then write to it with
  677. /// a CodedOutputStream. Calling CheckNoSpaceLeft after writing verifies that
  678. /// the message was actually as big as expected, which can help bugs.
  679. /// </summary>
  680. public void CheckNoSpaceLeft()
  681. {
  682. if (SpaceLeft != 0)
  683. {
  684. throw new InvalidOperationException("Did not write as much data as expected.");
  685. }
  686. }
  687. /// <summary>
  688. /// If writing to a flat array, returns the space left in the array. Otherwise,
  689. /// throws an InvalidOperationException.
  690. /// </summary>
  691. public int SpaceLeft
  692. {
  693. get
  694. {
  695. if (output == null)
  696. {
  697. return limit - position;
  698. }
  699. else
  700. {
  701. throw new InvalidOperationException(
  702. "SpaceLeft can only be called on CodedOutputStreams that are " +
  703. "writing to a flat array.");
  704. }
  705. }
  706. }
  707. }
  708. }