CodedOutputStream.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  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.Security;
  36. using System.Text;
  37. namespace Google.Protobuf
  38. {
  39. /// <summary>
  40. /// Encodes and writes protocol message fields.
  41. /// </summary>
  42. /// <remarks>
  43. /// <para>
  44. /// This class is generally used by generated code to write appropriate
  45. /// primitives to the stream. It effectively encapsulates the lowest
  46. /// levels of protocol buffer format. Unlike some other implementations,
  47. /// this does not include combined "write tag and value" methods. Generated
  48. /// code knows the exact byte representations of the tags they're going to write,
  49. /// so there's no need to re-encode them each time. Manually-written code calling
  50. /// this class should just call one of the <c>WriteTag</c> overloads before each value.
  51. /// </para>
  52. /// <para>
  53. /// Repeated fields and map fields are not handled by this class; use <c>RepeatedField&lt;T&gt;</c>
  54. /// and <c>MapField&lt;TKey, TValue&gt;</c> to serialize such fields.
  55. /// </para>
  56. /// </remarks>
  57. [SecuritySafeCritical]
  58. public sealed partial class CodedOutputStream : IDisposable
  59. {
  60. // "Local" copy of Encoding.UTF8, for efficiency. (Yes, it makes a difference.)
  61. internal static readonly Encoding Utf8Encoding = Encoding.UTF8;
  62. /// <summary>
  63. /// The buffer size used by CreateInstance(Stream).
  64. /// </summary>
  65. public static readonly int DefaultBufferSize = 4096;
  66. private readonly bool leaveOpen;
  67. private readonly byte[] buffer;
  68. private WriterInternalState state;
  69. private readonly Stream output;
  70. #region Construction
  71. /// <summary>
  72. /// Creates a new CodedOutputStream that writes directly to the given
  73. /// byte array. If more bytes are written than fit in the array,
  74. /// OutOfSpaceException will be thrown.
  75. /// </summary>
  76. public CodedOutputStream(byte[] flatArray) : this(flatArray, 0, flatArray.Length)
  77. {
  78. }
  79. /// <summary>
  80. /// Creates a new CodedOutputStream that writes directly to the given
  81. /// byte array slice. If more bytes are written than fit in the array,
  82. /// OutOfSpaceException will be thrown.
  83. /// </summary>
  84. private CodedOutputStream(byte[] buffer, int offset, int length)
  85. {
  86. this.output = null;
  87. this.buffer = ProtoPreconditions.CheckNotNull(buffer, nameof(buffer));
  88. this.state.position = offset;
  89. this.state.limit = offset + length;
  90. WriteBufferHelper.Initialize(this, out this.state.writeBufferHelper);
  91. leaveOpen = true; // Simple way of avoiding trying to dispose of a null reference
  92. }
  93. private CodedOutputStream(Stream output, byte[] buffer, bool leaveOpen)
  94. {
  95. this.output = ProtoPreconditions.CheckNotNull(output, nameof(output));
  96. this.buffer = buffer;
  97. this.state.position = 0;
  98. this.state.limit = buffer.Length;
  99. WriteBufferHelper.Initialize(this, out this.state.writeBufferHelper);
  100. this.leaveOpen = leaveOpen;
  101. }
  102. /// <summary>
  103. /// Creates a new <see cref="CodedOutputStream" /> which write to the given stream, and disposes of that
  104. /// stream when the returned <c>CodedOutputStream</c> is disposed.
  105. /// </summary>
  106. /// <param name="output">The stream to write to. It will be disposed when the returned <c>CodedOutputStream is disposed.</c></param>
  107. public CodedOutputStream(Stream output) : this(output, DefaultBufferSize, false)
  108. {
  109. }
  110. /// <summary>
  111. /// Creates a new CodedOutputStream which write to the given stream and uses
  112. /// the specified buffer size.
  113. /// </summary>
  114. /// <param name="output">The stream to write to. It will be disposed when the returned <c>CodedOutputStream is disposed.</c></param>
  115. /// <param name="bufferSize">The size of buffer to use internally.</param>
  116. public CodedOutputStream(Stream output, int bufferSize) : this(output, new byte[bufferSize], false)
  117. {
  118. }
  119. /// <summary>
  120. /// Creates a new CodedOutputStream which write to the given stream.
  121. /// </summary>
  122. /// <param name="output">The stream to write to.</param>
  123. /// <param name="leaveOpen">If <c>true</c>, <paramref name="output"/> is left open when the returned <c>CodedOutputStream</c> is disposed;
  124. /// if <c>false</c>, the provided stream is disposed as well.</param>
  125. public CodedOutputStream(Stream output, bool leaveOpen) : this(output, DefaultBufferSize, leaveOpen)
  126. {
  127. }
  128. /// <summary>
  129. /// Creates a new CodedOutputStream which write to the given stream and uses
  130. /// the specified buffer size.
  131. /// </summary>
  132. /// <param name="output">The stream to write to.</param>
  133. /// <param name="bufferSize">The size of buffer to use internally.</param>
  134. /// <param name="leaveOpen">If <c>true</c>, <paramref name="output"/> is left open when the returned <c>CodedOutputStream</c> is disposed;
  135. /// if <c>false</c>, the provided stream is disposed as well.</param>
  136. public CodedOutputStream(Stream output, int bufferSize, bool leaveOpen) : this(output, new byte[bufferSize], leaveOpen)
  137. {
  138. }
  139. #endregion
  140. /// <summary>
  141. /// Returns the current position in the stream, or the position in the output buffer
  142. /// </summary>
  143. public long Position
  144. {
  145. get
  146. {
  147. if (output != null)
  148. {
  149. return output.Position + state.position;
  150. }
  151. return state.position;
  152. }
  153. }
  154. #region Writing of values (not including tags)
  155. /// <summary>
  156. /// Writes a double field value, without a tag, to the stream.
  157. /// </summary>
  158. /// <param name="value">The value to write</param>
  159. public void WriteDouble(double value)
  160. {
  161. var span = new Span<byte>(buffer);
  162. WritingPrimitives.WriteDouble(ref span, ref state, value);
  163. }
  164. /// <summary>
  165. /// Writes a float field value, without a tag, to the stream.
  166. /// </summary>
  167. /// <param name="value">The value to write</param>
  168. public void WriteFloat(float value)
  169. {
  170. var span = new Span<byte>(buffer);
  171. WritingPrimitives.WriteFloat(ref span, ref state, value);
  172. }
  173. /// <summary>
  174. /// Writes a uint64 field value, without a tag, to the stream.
  175. /// </summary>
  176. /// <param name="value">The value to write</param>
  177. public void WriteUInt64(ulong value)
  178. {
  179. var span = new Span<byte>(buffer);
  180. WritingPrimitives.WriteUInt64(ref span, ref state, value);
  181. }
  182. /// <summary>
  183. /// Writes an int64 field value, without a tag, to the stream.
  184. /// </summary>
  185. /// <param name="value">The value to write</param>
  186. public void WriteInt64(long value)
  187. {
  188. var span = new Span<byte>(buffer);
  189. WritingPrimitives.WriteInt64(ref span, ref state, value);
  190. }
  191. /// <summary>
  192. /// Writes an int32 field value, without a tag, to the stream.
  193. /// </summary>
  194. /// <param name="value">The value to write</param>
  195. public void WriteInt32(int value)
  196. {
  197. var span = new Span<byte>(buffer);
  198. WritingPrimitives.WriteInt32(ref span, ref state, value);
  199. }
  200. /// <summary>
  201. /// Writes a fixed64 field value, without a tag, to the stream.
  202. /// </summary>
  203. /// <param name="value">The value to write</param>
  204. public void WriteFixed64(ulong value)
  205. {
  206. var span = new Span<byte>(buffer);
  207. WritingPrimitives.WriteFixed64(ref span, ref state, value);
  208. }
  209. /// <summary>
  210. /// Writes a fixed32 field value, without a tag, to the stream.
  211. /// </summary>
  212. /// <param name="value">The value to write</param>
  213. public void WriteFixed32(uint value)
  214. {
  215. var span = new Span<byte>(buffer);
  216. WritingPrimitives.WriteFixed32(ref span, ref state, value);
  217. }
  218. /// <summary>
  219. /// Writes a bool field value, without a tag, to the stream.
  220. /// </summary>
  221. /// <param name="value">The value to write</param>
  222. public void WriteBool(bool value)
  223. {
  224. var span = new Span<byte>(buffer);
  225. WritingPrimitives.WriteBool(ref span, ref state, value);
  226. }
  227. /// <summary>
  228. /// Writes a string field value, without a tag, to the stream.
  229. /// The data is length-prefixed.
  230. /// </summary>
  231. /// <param name="value">The value to write</param>
  232. public void WriteString(string value)
  233. {
  234. var span = new Span<byte>(buffer);
  235. WritingPrimitives.WriteString(ref span, ref state, value);
  236. }
  237. /// <summary>
  238. /// Writes a message, without a tag, to the stream.
  239. /// The data is length-prefixed.
  240. /// </summary>
  241. /// <param name="value">The value to write</param>
  242. public void WriteMessage(IMessage value)
  243. {
  244. // TODO(jtattermusch): if the message doesn't implement IBufferMessage (and thus does not provide the InternalWriteTo method),
  245. // what we're doing here works fine, but could be more efficient.
  246. // For now, this inefficiency is fine, considering this is only a backward-compatibility scenario (and regenerating the code fixes it).
  247. var span = new Span<byte>(buffer);
  248. WriteContext.Initialize(ref span, ref state, out WriteContext ctx);
  249. try
  250. {
  251. WritingPrimitivesMessages.WriteMessage(ref ctx, value);
  252. }
  253. finally
  254. {
  255. ctx.CopyStateTo(this);
  256. }
  257. }
  258. /// <summary>
  259. /// Writes a message, without a tag, to the stream.
  260. /// Only the message data is written, without a length-delimiter.
  261. /// </summary>
  262. /// <param name="value">The value to write</param>
  263. public void WriteRawMessage(IMessage value)
  264. {
  265. // TODO(jtattermusch): if the message doesn't implement IBufferMessage (and thus does not provide the InternalWriteTo method),
  266. // what we're doing here works fine, but could be more efficient.
  267. // For now, this inefficiency is fine, considering this is only a backward-compatibility scenario (and regenerating the code fixes it).
  268. var span = new Span<byte>(buffer);
  269. WriteContext.Initialize(ref span, ref state, out WriteContext ctx);
  270. try
  271. {
  272. // TODO: fix fix fix
  273. WritingPrimitivesMessages.WriteMessage(ref ctx, value);
  274. }
  275. finally
  276. {
  277. ctx.CopyStateTo(this);
  278. }
  279. }
  280. /// <summary>
  281. /// Writes a group, without a tag, to the stream.
  282. /// </summary>
  283. /// <param name="value">The value to write</param>
  284. public void WriteGroup(IMessage value)
  285. {
  286. var span = new Span<byte>(buffer);
  287. WriteContext.Initialize(ref span, ref state, out WriteContext ctx);
  288. try
  289. {
  290. WritingPrimitivesMessages.WriteGroup(ref ctx, value);
  291. }
  292. finally
  293. {
  294. ctx.CopyStateTo(this);
  295. }
  296. }
  297. /// <summary>
  298. /// Write a byte string, without a tag, to the stream.
  299. /// The data is length-prefixed.
  300. /// </summary>
  301. /// <param name="value">The value to write</param>
  302. public void WriteBytes(ByteString value)
  303. {
  304. var span = new Span<byte>(buffer);
  305. WritingPrimitives.WriteBytes(ref span, ref state, value);
  306. }
  307. /// <summary>
  308. /// Writes a uint32 value, without a tag, to the stream.
  309. /// </summary>
  310. /// <param name="value">The value to write</param>
  311. public void WriteUInt32(uint value)
  312. {
  313. var span = new Span<byte>(buffer);
  314. WritingPrimitives.WriteUInt32(ref span, ref state, value);
  315. }
  316. /// <summary>
  317. /// Writes an enum value, without a tag, to the stream.
  318. /// </summary>
  319. /// <param name="value">The value to write</param>
  320. public void WriteEnum(int value)
  321. {
  322. var span = new Span<byte>(buffer);
  323. WritingPrimitives.WriteEnum(ref span, ref state, value);
  324. }
  325. /// <summary>
  326. /// Writes an sfixed32 value, without a tag, to the stream.
  327. /// </summary>
  328. /// <param name="value">The value to write.</param>
  329. public void WriteSFixed32(int value)
  330. {
  331. var span = new Span<byte>(buffer);
  332. WritingPrimitives.WriteSFixed32(ref span, ref state, value);
  333. }
  334. /// <summary>
  335. /// Writes an sfixed64 value, without a tag, to the stream.
  336. /// </summary>
  337. /// <param name="value">The value to write</param>
  338. public void WriteSFixed64(long value)
  339. {
  340. var span = new Span<byte>(buffer);
  341. WritingPrimitives.WriteSFixed64(ref span, ref state, value);
  342. }
  343. /// <summary>
  344. /// Writes an sint32 value, without a tag, to the stream.
  345. /// </summary>
  346. /// <param name="value">The value to write</param>
  347. public void WriteSInt32(int value)
  348. {
  349. var span = new Span<byte>(buffer);
  350. WritingPrimitives.WriteSInt32(ref span, ref state, value);
  351. }
  352. /// <summary>
  353. /// Writes an sint64 value, without a tag, to the stream.
  354. /// </summary>
  355. /// <param name="value">The value to write</param>
  356. public void WriteSInt64(long value)
  357. {
  358. var span = new Span<byte>(buffer);
  359. WritingPrimitives.WriteSInt64(ref span, ref state, value);
  360. }
  361. /// <summary>
  362. /// Writes a length (in bytes) for length-delimited data.
  363. /// </summary>
  364. /// <remarks>
  365. /// This method simply writes a rawint, but exists for clarity in calling code.
  366. /// </remarks>
  367. /// <param name="length">Length value, in bytes.</param>
  368. public void WriteLength(int length)
  369. {
  370. var span = new Span<byte>(buffer);
  371. WritingPrimitives.WriteLength(ref span, ref state, length);
  372. }
  373. #endregion
  374. #region Raw tag writing
  375. /// <summary>
  376. /// Encodes and writes a tag.
  377. /// </summary>
  378. /// <param name="fieldNumber">The number of the field to write the tag for</param>
  379. /// <param name="type">The wire format type of the tag to write</param>
  380. public void WriteTag(int fieldNumber, WireFormat.WireType type)
  381. {
  382. var span = new Span<byte>(buffer);
  383. WritingPrimitives.WriteTag(ref span, ref state, fieldNumber, type);
  384. }
  385. /// <summary>
  386. /// Writes an already-encoded tag.
  387. /// </summary>
  388. /// <param name="tag">The encoded tag</param>
  389. public void WriteTag(uint tag)
  390. {
  391. var span = new Span<byte>(buffer);
  392. WritingPrimitives.WriteTag(ref span, ref state, tag);
  393. }
  394. /// <summary>
  395. /// Writes the given single-byte tag directly to the stream.
  396. /// </summary>
  397. /// <param name="b1">The encoded tag</param>
  398. public void WriteRawTag(byte b1)
  399. {
  400. var span = new Span<byte>(buffer);
  401. WritingPrimitives.WriteRawTag(ref span, ref state, b1);
  402. }
  403. /// <summary>
  404. /// Writes the given two-byte tag directly to the stream.
  405. /// </summary>
  406. /// <param name="b1">The first byte of the encoded tag</param>
  407. /// <param name="b2">The second byte of the encoded tag</param>
  408. public void WriteRawTag(byte b1, byte b2)
  409. {
  410. var span = new Span<byte>(buffer);
  411. WritingPrimitives.WriteRawTag(ref span, ref state, b1, b2);
  412. }
  413. /// <summary>
  414. /// Writes the given three-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. public void WriteRawTag(byte b1, byte b2, byte b3)
  420. {
  421. var span = new Span<byte>(buffer);
  422. WritingPrimitives.WriteRawTag(ref span, ref state, b1, b2, b3);
  423. }
  424. /// <summary>
  425. /// Writes the given four-byte tag directly to the stream.
  426. /// </summary>
  427. /// <param name="b1">The first byte of the encoded tag</param>
  428. /// <param name="b2">The second byte of the encoded tag</param>
  429. /// <param name="b3">The third byte of the encoded tag</param>
  430. /// <param name="b4">The fourth byte of the encoded tag</param>
  431. public void WriteRawTag(byte b1, byte b2, byte b3, byte b4)
  432. {
  433. var span = new Span<byte>(buffer);
  434. WritingPrimitives.WriteRawTag(ref span, ref state, b1, b2, b3, b4);
  435. }
  436. /// <summary>
  437. /// Writes the given five-byte tag directly to the stream.
  438. /// </summary>
  439. /// <param name="b1">The first byte of the encoded tag</param>
  440. /// <param name="b2">The second byte of the encoded tag</param>
  441. /// <param name="b3">The third byte of the encoded tag</param>
  442. /// <param name="b4">The fourth byte of the encoded tag</param>
  443. /// <param name="b5">The fifth byte of the encoded tag</param>
  444. public void WriteRawTag(byte b1, byte b2, byte b3, byte b4, byte b5)
  445. {
  446. var span = new Span<byte>(buffer);
  447. WritingPrimitives.WriteRawTag(ref span, ref state, b1, b2, b3, b4, b5);
  448. }
  449. #endregion
  450. #region Underlying writing primitives
  451. /// <summary>
  452. /// Writes a 32 bit value as a varint. The fast route is taken when
  453. /// there's enough buffer space left to whizz through without checking
  454. /// for each byte; otherwise, we resort to calling WriteRawByte each time.
  455. /// </summary>
  456. internal void WriteRawVarint32(uint value)
  457. {
  458. var span = new Span<byte>(buffer);
  459. WritingPrimitives.WriteRawVarint32(ref span, ref state, value);
  460. }
  461. internal void WriteRawVarint64(ulong value)
  462. {
  463. var span = new Span<byte>(buffer);
  464. WritingPrimitives.WriteRawVarint64(ref span, ref state, value);
  465. }
  466. internal void WriteRawLittleEndian32(uint value)
  467. {
  468. var span = new Span<byte>(buffer);
  469. WritingPrimitives.WriteRawLittleEndian32(ref span, ref state, value);
  470. }
  471. internal void WriteRawLittleEndian64(ulong value)
  472. {
  473. var span = new Span<byte>(buffer);
  474. WritingPrimitives.WriteRawLittleEndian64(ref span, ref state, value);
  475. }
  476. internal void WriteRawByte(byte value)
  477. {
  478. var span = new Span<byte>(buffer);
  479. WritingPrimitives.WriteRawByte(ref span, ref state, value);
  480. }
  481. internal void WriteRawByte(uint value)
  482. {
  483. var span = new Span<byte>(buffer);
  484. WritingPrimitives.WriteRawByte(ref span, ref state, value);
  485. }
  486. /// <summary>
  487. /// Writes out an array of bytes.
  488. /// </summary>
  489. internal void WriteRawBytes(byte[] value)
  490. {
  491. WriteRawBytes(value, 0, value.Length);
  492. }
  493. /// <summary>
  494. /// Writes out part of an array of bytes.
  495. /// </summary>
  496. internal void WriteRawBytes(byte[] value, int offset, int length)
  497. {
  498. var span = new Span<byte>(buffer);
  499. WritingPrimitives.WriteRawBytes(ref span, ref state, value, offset, length);
  500. }
  501. #endregion
  502. ///// <summary>
  503. ///// Encode a 32-bit value with ZigZag encoding.
  504. ///// </summary>
  505. ///// <remarks>
  506. ///// ZigZag encodes signed integers into values that can be efficiently
  507. ///// encoded with varint. (Otherwise, negative values must be
  508. ///// sign-extended to 64 bits to be varint encoded, thus always taking
  509. ///// 10 bytes on the wire.)
  510. ///// </remarks>
  511. //internal static uint EncodeZigZag32(int n)
  512. //{
  513. // // Note: the right-shift must be arithmetic
  514. // return (uint) ((n << 1) ^ (n >> 31));
  515. //}
  516. ///// <summary>
  517. ///// Encode a 64-bit value with ZigZag encoding.
  518. ///// </summary>
  519. ///// <remarks>
  520. ///// ZigZag encodes signed integers into values that can be efficiently
  521. ///// encoded with varint. (Otherwise, negative values must be
  522. ///// sign-extended to 64 bits to be varint encoded, thus always taking
  523. ///// 10 bytes on the wire.)
  524. ///// </remarks>
  525. //internal static ulong EncodeZigZag64(long n)
  526. //{
  527. // return (ulong) ((n << 1) ^ (n >> 63));
  528. //}
  529. //private void RefreshBuffer()
  530. //{
  531. // if (output == null)
  532. // {
  533. // // We're writing to a single buffer.
  534. // throw new OutOfSpaceException();
  535. // }
  536. // // Since we have an output stream, this is our buffer
  537. // // and buffer offset == 0
  538. // output.Write(buffer, 0, position);
  539. // position = 0;
  540. //}
  541. /// <summary>
  542. /// Indicates that a CodedOutputStream wrapping a flat byte array
  543. /// ran out of space.
  544. /// </summary>
  545. public sealed class OutOfSpaceException : IOException
  546. {
  547. internal OutOfSpaceException()
  548. : base("CodedOutputStream was writing to a flat byte array and ran out of space.")
  549. {
  550. }
  551. }
  552. /// <summary>
  553. /// Flushes any buffered data and optionally closes the underlying stream, if any.
  554. /// </summary>
  555. /// <remarks>
  556. /// <para>
  557. /// By default, any underlying stream is closed by this method. To configure this behaviour,
  558. /// use a constructor overload with a <c>leaveOpen</c> parameter. If this instance does not
  559. /// have an underlying stream, this method does nothing.
  560. /// </para>
  561. /// <para>
  562. /// For the sake of efficiency, calling this method does not prevent future write calls - but
  563. /// if a later write ends up writing to a stream which has been disposed, that is likely to
  564. /// fail. It is recommend that you not call any other methods after this.
  565. /// </para>
  566. /// </remarks>
  567. public void Dispose()
  568. {
  569. Flush();
  570. if (!leaveOpen)
  571. {
  572. output.Dispose();
  573. }
  574. }
  575. /// <summary>
  576. /// Flushes any buffered data to the underlying stream (if there is one).
  577. /// </summary>
  578. public void Flush()
  579. {
  580. var span = new Span<byte>(buffer);
  581. state.writeBufferHelper.Flush(ref span, ref state);
  582. /*if (output != null)
  583. {
  584. RefreshBuffer();
  585. }*/
  586. }
  587. /// <summary>
  588. /// Verifies that SpaceLeft returns zero. It's common to create a byte array
  589. /// that is exactly big enough to hold a message, then write to it with
  590. /// a CodedOutputStream. Calling CheckNoSpaceLeft after writing verifies that
  591. /// the message was actually as big as expected, which can help bugs.
  592. /// </summary>
  593. public void CheckNoSpaceLeft()
  594. {
  595. if (SpaceLeft != 0)
  596. {
  597. throw new InvalidOperationException("Did not write as much data as expected.");
  598. }
  599. }
  600. /// <summary>
  601. /// If writing to a flat array, returns the space left in the array. Otherwise,
  602. /// throws an InvalidOperationException.
  603. /// </summary>
  604. public int SpaceLeft
  605. {
  606. get
  607. {
  608. if (output == null)
  609. {
  610. return state.limit - state.position;
  611. }
  612. else
  613. {
  614. throw new InvalidOperationException(
  615. "SpaceLeft can only be called on CodedOutputStreams that are " +
  616. "writing to a flat array.");
  617. }
  618. }
  619. }
  620. internal byte[] InternalBuffer => buffer;
  621. internal Stream InternalOutputStream => output;
  622. internal ref WriterInternalState InternalState => ref state;
  623. }
  624. }