CodedOutputStream.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  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. WritingPrimitivesMessages.WriteRawMessage(ref ctx, value);
  273. }
  274. finally
  275. {
  276. ctx.CopyStateTo(this);
  277. }
  278. }
  279. /// <summary>
  280. /// Writes a group, without a tag, to the stream.
  281. /// </summary>
  282. /// <param name="value">The value to write</param>
  283. public void WriteGroup(IMessage value)
  284. {
  285. var span = new Span<byte>(buffer);
  286. WriteContext.Initialize(ref span, ref state, out WriteContext ctx);
  287. try
  288. {
  289. WritingPrimitivesMessages.WriteGroup(ref ctx, value);
  290. }
  291. finally
  292. {
  293. ctx.CopyStateTo(this);
  294. }
  295. }
  296. /// <summary>
  297. /// Write a byte string, without a tag, to the stream.
  298. /// The data is length-prefixed.
  299. /// </summary>
  300. /// <param name="value">The value to write</param>
  301. public void WriteBytes(ByteString value)
  302. {
  303. var span = new Span<byte>(buffer);
  304. WritingPrimitives.WriteBytes(ref span, ref state, value);
  305. }
  306. /// <summary>
  307. /// Writes a uint32 value, without a tag, to the stream.
  308. /// </summary>
  309. /// <param name="value">The value to write</param>
  310. public void WriteUInt32(uint value)
  311. {
  312. var span = new Span<byte>(buffer);
  313. WritingPrimitives.WriteUInt32(ref span, ref state, value);
  314. }
  315. /// <summary>
  316. /// Writes an enum value, without a tag, to the stream.
  317. /// </summary>
  318. /// <param name="value">The value to write</param>
  319. public void WriteEnum(int value)
  320. {
  321. var span = new Span<byte>(buffer);
  322. WritingPrimitives.WriteEnum(ref span, ref state, value);
  323. }
  324. /// <summary>
  325. /// Writes an sfixed32 value, without a tag, to the stream.
  326. /// </summary>
  327. /// <param name="value">The value to write.</param>
  328. public void WriteSFixed32(int value)
  329. {
  330. var span = new Span<byte>(buffer);
  331. WritingPrimitives.WriteSFixed32(ref span, ref state, value);
  332. }
  333. /// <summary>
  334. /// Writes an sfixed64 value, without a tag, to the stream.
  335. /// </summary>
  336. /// <param name="value">The value to write</param>
  337. public void WriteSFixed64(long value)
  338. {
  339. var span = new Span<byte>(buffer);
  340. WritingPrimitives.WriteSFixed64(ref span, ref state, value);
  341. }
  342. /// <summary>
  343. /// Writes an sint32 value, without a tag, to the stream.
  344. /// </summary>
  345. /// <param name="value">The value to write</param>
  346. public void WriteSInt32(int value)
  347. {
  348. var span = new Span<byte>(buffer);
  349. WritingPrimitives.WriteSInt32(ref span, ref state, value);
  350. }
  351. /// <summary>
  352. /// Writes an sint64 value, without a tag, to the stream.
  353. /// </summary>
  354. /// <param name="value">The value to write</param>
  355. public void WriteSInt64(long value)
  356. {
  357. var span = new Span<byte>(buffer);
  358. WritingPrimitives.WriteSInt64(ref span, ref state, value);
  359. }
  360. /// <summary>
  361. /// Writes a length (in bytes) for length-delimited data.
  362. /// </summary>
  363. /// <remarks>
  364. /// This method simply writes a rawint, but exists for clarity in calling code.
  365. /// </remarks>
  366. /// <param name="length">Length value, in bytes.</param>
  367. public void WriteLength(int length)
  368. {
  369. var span = new Span<byte>(buffer);
  370. WritingPrimitives.WriteLength(ref span, ref state, length);
  371. }
  372. #endregion
  373. #region Raw tag writing
  374. /// <summary>
  375. /// Encodes and writes a tag.
  376. /// </summary>
  377. /// <param name="fieldNumber">The number of the field to write the tag for</param>
  378. /// <param name="type">The wire format type of the tag to write</param>
  379. public void WriteTag(int fieldNumber, WireFormat.WireType type)
  380. {
  381. var span = new Span<byte>(buffer);
  382. WritingPrimitives.WriteTag(ref span, ref state, fieldNumber, type);
  383. }
  384. /// <summary>
  385. /// Writes an already-encoded tag.
  386. /// </summary>
  387. /// <param name="tag">The encoded tag</param>
  388. public void WriteTag(uint tag)
  389. {
  390. var span = new Span<byte>(buffer);
  391. WritingPrimitives.WriteTag(ref span, ref state, tag);
  392. }
  393. /// <summary>
  394. /// Writes the given single-byte tag directly to the stream.
  395. /// </summary>
  396. /// <param name="b1">The encoded tag</param>
  397. public void WriteRawTag(byte b1)
  398. {
  399. var span = new Span<byte>(buffer);
  400. WritingPrimitives.WriteRawTag(ref span, ref state, b1);
  401. }
  402. /// <summary>
  403. /// Writes the given two-byte tag directly to the stream.
  404. /// </summary>
  405. /// <param name="b1">The first byte of the encoded tag</param>
  406. /// <param name="b2">The second byte of the encoded tag</param>
  407. public void WriteRawTag(byte b1, byte b2)
  408. {
  409. var span = new Span<byte>(buffer);
  410. WritingPrimitives.WriteRawTag(ref span, ref state, b1, b2);
  411. }
  412. /// <summary>
  413. /// Writes the given three-byte tag directly to the stream.
  414. /// </summary>
  415. /// <param name="b1">The first byte of the encoded tag</param>
  416. /// <param name="b2">The second byte of the encoded tag</param>
  417. /// <param name="b3">The third byte of the encoded tag</param>
  418. public void WriteRawTag(byte b1, byte b2, byte b3)
  419. {
  420. var span = new Span<byte>(buffer);
  421. WritingPrimitives.WriteRawTag(ref span, ref state, b1, b2, b3);
  422. }
  423. /// <summary>
  424. /// Writes the given four-byte tag directly to the stream.
  425. /// </summary>
  426. /// <param name="b1">The first byte of the encoded tag</param>
  427. /// <param name="b2">The second byte of the encoded tag</param>
  428. /// <param name="b3">The third byte of the encoded tag</param>
  429. /// <param name="b4">The fourth byte of the encoded tag</param>
  430. public void WriteRawTag(byte b1, byte b2, byte b3, byte b4)
  431. {
  432. var span = new Span<byte>(buffer);
  433. WritingPrimitives.WriteRawTag(ref span, ref state, b1, b2, b3, b4);
  434. }
  435. /// <summary>
  436. /// Writes the given five-byte tag directly to the stream.
  437. /// </summary>
  438. /// <param name="b1">The first byte of the encoded tag</param>
  439. /// <param name="b2">The second byte of the encoded tag</param>
  440. /// <param name="b3">The third byte of the encoded tag</param>
  441. /// <param name="b4">The fourth byte of the encoded tag</param>
  442. /// <param name="b5">The fifth byte of the encoded tag</param>
  443. public void WriteRawTag(byte b1, byte b2, byte b3, byte b4, byte b5)
  444. {
  445. var span = new Span<byte>(buffer);
  446. WritingPrimitives.WriteRawTag(ref span, ref state, b1, b2, b3, b4, b5);
  447. }
  448. #endregion
  449. #region Underlying writing primitives
  450. /// <summary>
  451. /// Writes a 32 bit value as a varint. The fast route is taken when
  452. /// there's enough buffer space left to whizz through without checking
  453. /// for each byte; otherwise, we resort to calling WriteRawByte each time.
  454. /// </summary>
  455. internal void WriteRawVarint32(uint value)
  456. {
  457. var span = new Span<byte>(buffer);
  458. WritingPrimitives.WriteRawVarint32(ref span, ref state, value);
  459. }
  460. internal void WriteRawVarint64(ulong value)
  461. {
  462. var span = new Span<byte>(buffer);
  463. WritingPrimitives.WriteRawVarint64(ref span, ref state, value);
  464. }
  465. internal void WriteRawLittleEndian32(uint value)
  466. {
  467. var span = new Span<byte>(buffer);
  468. WritingPrimitives.WriteRawLittleEndian32(ref span, ref state, value);
  469. }
  470. internal void WriteRawLittleEndian64(ulong value)
  471. {
  472. var span = new Span<byte>(buffer);
  473. WritingPrimitives.WriteRawLittleEndian64(ref span, ref state, value);
  474. }
  475. internal void WriteRawByte(byte value)
  476. {
  477. var span = new Span<byte>(buffer);
  478. WritingPrimitives.WriteRawByte(ref span, ref state, value);
  479. }
  480. internal void WriteRawByte(uint value)
  481. {
  482. var span = new Span<byte>(buffer);
  483. WritingPrimitives.WriteRawByte(ref span, ref state, value);
  484. }
  485. /// <summary>
  486. /// Writes out an array of bytes.
  487. /// </summary>
  488. internal void WriteRawBytes(byte[] value)
  489. {
  490. WriteRawBytes(value, 0, value.Length);
  491. }
  492. /// <summary>
  493. /// Writes out part of an array of bytes.
  494. /// </summary>
  495. internal void WriteRawBytes(byte[] value, int offset, int length)
  496. {
  497. var span = new Span<byte>(buffer);
  498. WritingPrimitives.WriteRawBytes(ref span, ref state, value, offset, length);
  499. }
  500. #endregion
  501. ///// <summary>
  502. ///// Encode a 32-bit value with ZigZag encoding.
  503. ///// </summary>
  504. ///// <remarks>
  505. ///// ZigZag encodes signed integers into values that can be efficiently
  506. ///// encoded with varint. (Otherwise, negative values must be
  507. ///// sign-extended to 64 bits to be varint encoded, thus always taking
  508. ///// 10 bytes on the wire.)
  509. ///// </remarks>
  510. //internal static uint EncodeZigZag32(int n)
  511. //{
  512. // // Note: the right-shift must be arithmetic
  513. // return (uint) ((n << 1) ^ (n >> 31));
  514. //}
  515. ///// <summary>
  516. ///// Encode a 64-bit value with ZigZag encoding.
  517. ///// </summary>
  518. ///// <remarks>
  519. ///// ZigZag encodes signed integers into values that can be efficiently
  520. ///// encoded with varint. (Otherwise, negative values must be
  521. ///// sign-extended to 64 bits to be varint encoded, thus always taking
  522. ///// 10 bytes on the wire.)
  523. ///// </remarks>
  524. //internal static ulong EncodeZigZag64(long n)
  525. //{
  526. // return (ulong) ((n << 1) ^ (n >> 63));
  527. //}
  528. //private void RefreshBuffer()
  529. //{
  530. // if (output == null)
  531. // {
  532. // // We're writing to a single buffer.
  533. // throw new OutOfSpaceException();
  534. // }
  535. // // Since we have an output stream, this is our buffer
  536. // // and buffer offset == 0
  537. // output.Write(buffer, 0, position);
  538. // position = 0;
  539. //}
  540. /// <summary>
  541. /// Indicates that a CodedOutputStream wrapping a flat byte array
  542. /// ran out of space.
  543. /// </summary>
  544. public sealed class OutOfSpaceException : IOException
  545. {
  546. internal OutOfSpaceException()
  547. : base("CodedOutputStream was writing to a flat byte array and ran out of space.")
  548. {
  549. }
  550. }
  551. /// <summary>
  552. /// Flushes any buffered data and optionally closes the underlying stream, if any.
  553. /// </summary>
  554. /// <remarks>
  555. /// <para>
  556. /// By default, any underlying stream is closed by this method. To configure this behaviour,
  557. /// use a constructor overload with a <c>leaveOpen</c> parameter. If this instance does not
  558. /// have an underlying stream, this method does nothing.
  559. /// </para>
  560. /// <para>
  561. /// For the sake of efficiency, calling this method does not prevent future write calls - but
  562. /// if a later write ends up writing to a stream which has been disposed, that is likely to
  563. /// fail. It is recommend that you not call any other methods after this.
  564. /// </para>
  565. /// </remarks>
  566. public void Dispose()
  567. {
  568. Flush();
  569. if (!leaveOpen)
  570. {
  571. output.Dispose();
  572. }
  573. }
  574. /// <summary>
  575. /// Flushes any buffered data to the underlying stream (if there is one).
  576. /// </summary>
  577. public void Flush()
  578. {
  579. var span = new Span<byte>(buffer);
  580. WriteBufferHelper.Flush(ref span, ref state);
  581. /*if (output != null)
  582. {
  583. RefreshBuffer();
  584. }*/
  585. }
  586. /// <summary>
  587. /// Verifies that SpaceLeft returns zero. It's common to create a byte array
  588. /// that is exactly big enough to hold a message, then write to it with
  589. /// a CodedOutputStream. Calling CheckNoSpaceLeft after writing verifies that
  590. /// the message was actually as big as expected, which can help finding bugs.
  591. /// </summary>
  592. public void CheckNoSpaceLeft()
  593. {
  594. WriteBufferHelper.CheckNoSpaceLeft(ref state);
  595. }
  596. /// <summary>
  597. /// If writing to a flat array, returns the space left in the array. Otherwise,
  598. /// throws an InvalidOperationException.
  599. /// </summary>
  600. public int SpaceLeft => WriteBufferHelper.GetSpaceLeft(ref state);
  601. internal byte[] InternalBuffer => buffer;
  602. internal Stream InternalOutputStream => output;
  603. internal ref WriterInternalState InternalState => ref state;
  604. }
  605. }