CodedOutputStream.cs 27.5 KB
Newer Older
1 2 3
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc.  All rights reserved.
4
// https://developers.google.com/protocol-buffers/
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion

33
using Google.Protobuf.Collections;
34 35 36 37
using System;
using System.IO;
using System.Text;

38
namespace Google.Protobuf
39 40 41 42 43
{
    /// <summary>
    /// Encodes and writes protocol message fields.
    /// </summary>
    /// <remarks>
44 45 46 47 48 49 50 51 52 53
    /// <para>
    /// This class is generally used by generated code to write appropriate
    /// primitives to the stream. It effectively encapsulates the lowest
    /// levels of protocol buffer format. Unlike some other implementations,
    /// this does not include combined "write tag and value" methods. Generated
    /// code knows the exact byte representations of the tags they're going to write,
    /// so there's no need to re-encode them each time. Manually-written code calling
    /// this class should just call one of the <c>WriteTag</c> overloads before each value.
    /// </para>
    /// <para>
54 55
    /// Repeated fields and map fields are not handled by this class; use <c>RepeatedField&lt;T&gt;</c>
    /// and <c>MapField&lt;TKey, TValue&gt;</c> to serialize such fields.
56
    /// </para>
57
    /// </remarks>
58
    public sealed partial class CodedOutputStream : IDisposable
59
    {
60 61
        // "Local" copy of Encoding.UTF8, for efficiency. (Yes, it makes a difference.)
        internal static readonly Encoding Utf8Encoding = Encoding.UTF8;
62

63 64 65 66 67
        /// <summary>
        /// The buffer size used by CreateInstance(Stream).
        /// </summary>
        public static readonly int DefaultBufferSize = 4096;

68
        private readonly bool leaveOpen;
69 70 71 72 73 74
        private readonly byte[] buffer;
        private readonly int limit;
        private int position;
        private readonly Stream output;

        #region Construction
75 76 77 78 79 80 81 82
        /// <summary>
        /// Creates a new CodedOutputStream that writes directly to the given
        /// byte array. If more bytes are written than fit in the array,
        /// OutOfSpaceException will be thrown.
        /// </summary>
        public CodedOutputStream(byte[] flatArray) : this(flatArray, 0, flatArray.Length)
        {
        }
83

84 85 86 87 88
        /// <summary>
        /// Creates a new CodedOutputStream that writes directly to the given
        /// byte array slice. If more bytes are written than fit in the array,
        /// OutOfSpaceException will be thrown.
        /// </summary>
89 90 91 92 93 94
        private CodedOutputStream(byte[] buffer, int offset, int length)
        {
            this.output = null;
            this.buffer = buffer;
            this.position = offset;
            this.limit = offset + length;
95
            leaveOpen = true; // Simple way of avoiding trying to dispose of a null reference
96 97
        }

98
        private CodedOutputStream(Stream output, byte[] buffer, bool leaveOpen)
99
        {
100
            this.output = ProtoPreconditions.CheckNotNull(output, nameof(output));
101 102 103
            this.buffer = buffer;
            this.position = 0;
            this.limit = buffer.Length;
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
            this.leaveOpen = leaveOpen;
        }

        /// <summary>
        /// Creates a new <see cref="CodedOutputStream" /> which write to the given stream, and disposes of that
        /// stream when the returned <c>CodedOutputStream</c> is disposed.
        /// </summary>
        /// <param name="output">The stream to write to. It will be disposed when the returned <c>CodedOutputStream is disposed.</c></param>
        public CodedOutputStream(Stream output) : this(output, DefaultBufferSize, false)
        {
        }

        /// <summary>
        /// Creates a new CodedOutputStream which write to the given stream and uses
        /// the specified buffer size.
        /// </summary>
        /// <param name="output">The stream to write to. It will be disposed when the returned <c>CodedOutputStream is disposed.</c></param>
        /// <param name="bufferSize">The size of buffer to use internally.</param>
        public CodedOutputStream(Stream output, int bufferSize) : this(output, new byte[bufferSize], false)
        {
124 125 126 127 128
        }

        /// <summary>
        /// Creates a new CodedOutputStream which write to the given stream.
        /// </summary>
129 130 131 132
        /// <param name="output">The stream to write to.</param>
        /// <param name="leaveOpen">If <c>true</c>, <paramref name="output"/> is left open when the returned <c>CodedOutputStream</c> is disposed;
        /// if <c>false</c>, the provided stream is disposed as well.</param>
        public CodedOutputStream(Stream output, bool leaveOpen) : this(output, DefaultBufferSize, leaveOpen)
133 134 135 136 137 138 139
        {
        }

        /// <summary>
        /// Creates a new CodedOutputStream which write to the given stream and uses
        /// the specified buffer size.
        /// </summary>
140 141 142 143 144
        /// <param name="output">The stream to write to.</param>
        /// <param name="bufferSize">The size of buffer to use internally.</param>
        /// <param name="leaveOpen">If <c>true</c>, <paramref name="output"/> is left open when the returned <c>CodedOutputStream</c> is disposed;
        /// if <c>false</c>, the provided stream is disposed as well.</param>
        public CodedOutputStream(Stream output, int bufferSize, bool leaveOpen) : this(output, new byte[bufferSize], leaveOpen)
145
        {
146
        }
147
        #endregion
148 149 150 151 152 153 154 155 156

        /// <summary>
        /// Returns the current position in the stream, or the position in the output buffer
        /// </summary>
        public long Position
        {
            get
            {
                if (output != null)
157
                {
158
                    return output.Position + position;
159
                }
160 161 162 163
                return position;
            }
        }

164
        #region Writing of values (not including tags)
165 166

        /// <summary>
167
        /// Writes a double field value, without a tag, to the stream.
168
        /// </summary>
169
        /// <param name="value">The value to write</param>
170
        public void WriteDouble(double value)
171
        {
Jon Skeet's avatar
Jon Skeet committed
172
            WriteRawLittleEndian64((ulong)BitConverter.DoubleToInt64Bits(value));
173 174 175 176 177
        }

        /// <summary>
        /// Writes a float field value, without a tag, to the stream.
        /// </summary>
178
        /// <param name="value">The value to write</param>
179
        public void WriteFloat(float value)
180 181
        {
            byte[] rawBytes = BitConverter.GetBytes(value);
182
            if (!BitConverter.IsLittleEndian)
183
            {
184
                ByteArray.Reverse(rawBytes);
185
            }
186 187 188 189 190 191 192 193 194

            if (limit - position >= 4)
            {
                buffer[position++] = rawBytes[0];
                buffer[position++] = rawBytes[1];
                buffer[position++] = rawBytes[2];
                buffer[position++] = rawBytes[3];
            }
            else
195
            {
196
                WriteRawBytes(rawBytes, 0, 4);
197
            }
198 199 200 201 202
        }

        /// <summary>
        /// Writes a uint64 field value, without a tag, to the stream.
        /// </summary>
203
        /// <param name="value">The value to write</param>
204
        public void WriteUInt64(ulong value)
205 206 207 208 209 210 211
        {
            WriteRawVarint64(value);
        }

        /// <summary>
        /// Writes an int64 field value, without a tag, to the stream.
        /// </summary>
212
        /// <param name="value">The value to write</param>
213
        public void WriteInt64(long value)
214
        {
215
            WriteRawVarint64((ulong) value);
216 217 218 219 220
        }

        /// <summary>
        /// Writes an int32 field value, without a tag, to the stream.
        /// </summary>
221
        /// <param name="value">The value to write</param>
222
        public void WriteInt32(int value)
223 224 225
        {
            if (value >= 0)
            {
226
                WriteRawVarint32((uint) value);
227 228 229 230
            }
            else
            {
                // Must sign-extend.
231
                WriteRawVarint64((ulong) value);
232 233 234 235 236 237
            }
        }

        /// <summary>
        /// Writes a fixed64 field value, without a tag, to the stream.
        /// </summary>
238
        /// <param name="value">The value to write</param>
239
        public void WriteFixed64(ulong value)
240 241 242 243 244 245 246
        {
            WriteRawLittleEndian64(value);
        }

        /// <summary>
        /// Writes a fixed32 field value, without a tag, to the stream.
        /// </summary>
247
        /// <param name="value">The value to write</param>
248
        public void WriteFixed32(uint value)
249 250 251 252 253 254 255
        {
            WriteRawLittleEndian32(value);
        }

        /// <summary>
        /// Writes a bool field value, without a tag, to the stream.
        /// </summary>
256
        /// <param name="value">The value to write</param>
257
        public void WriteBool(bool value)
258
        {
259
            WriteRawByte(value ? (byte) 1 : (byte) 0);
260 261 262 263
        }

        /// <summary>
        /// Writes a string field value, without a tag, to the stream.
264
        /// The data is length-prefixed.
265
        /// </summary>
266
        /// <param name="value">The value to write</param>
267
        public void WriteString(string value)
268 269 270
        {
            // Optimise the case where we have enough space to write
            // the string directly to the buffer, which should be common.
271
            int length = Utf8Encoding.GetByteCount(value);
272
            WriteLength(length);
273 274
            if (limit - position >= length)
            {
275 276 277 278 279 280 281 282 283
                if (length == value.Length) // Must be all ASCII...
                {
                    for (int i = 0; i < length; i++)
                    {
                        buffer[position + i] = (byte)value[i];
                    }
                }
                else
                {
284
                    Utf8Encoding.GetBytes(value, 0, value.Length, buffer, position);
285
                }
286 287 288 289
                position += length;
            }
            else
            {
290
                byte[] bytes = Utf8Encoding.GetBytes(value);
291 292 293 294
                WriteRawBytes(bytes);
            }
        }

295 296 297 298 299
        /// <summary>
        /// Writes a message, without a tag, to the stream.
        /// The data is length-prefixed.
        /// </summary>
        /// <param name="value">The value to write</param>
300
        public void WriteMessage(IMessage value)
301
        {
302
            WriteLength(value.CalculateSize());
303 304 305
            value.WriteTo(this);
        }

306 307 308 309 310
        /// <summary>
        /// Write a byte string, without a tag, to the stream.
        /// The data is length-prefixed.
        /// </summary>
        /// <param name="value">The value to write</param>
311
        public void WriteBytes(ByteString value)
312
        {
313
            WriteLength(value.Length);
314
            value.WriteRawBytesTo(this);
315 316
        }

317 318 319 320
        /// <summary>
        /// Writes a uint32 value, without a tag, to the stream.
        /// </summary>
        /// <param name="value">The value to write</param>
321
        public void WriteUInt32(uint value)
322 323 324 325
        {
            WriteRawVarint32(value);
        }

326 327 328 329
        /// <summary>
        /// Writes an enum value, without a tag, to the stream.
        /// </summary>
        /// <param name="value">The value to write</param>
330
        public void WriteEnum(int value)
331
        {
332
            WriteInt32(value);
333 334
        }

335 336 337 338
        /// <summary>
        /// Writes an sfixed32 value, without a tag, to the stream.
        /// </summary>
        /// <param name="value">The value to write.</param>
339
        public void WriteSFixed32(int value)
340
        {
341
            WriteRawLittleEndian32((uint) value);
342 343
        }

344 345 346 347
        /// <summary>
        /// Writes an sfixed64 value, without a tag, to the stream.
        /// </summary>
        /// <param name="value">The value to write</param>
348
        public void WriteSFixed64(long value)
349
        {
350
            WriteRawLittleEndian64((ulong) value);
351 352
        }

353 354 355 356
        /// <summary>
        /// Writes an sint32 value, without a tag, to the stream.
        /// </summary>
        /// <param name="value">The value to write</param>
357
        public void WriteSInt32(int value)
358 359 360 361
        {
            WriteRawVarint32(EncodeZigZag32(value));
        }

362 363 364 365
        /// <summary>
        /// Writes an sint64 value, without a tag, to the stream.
        /// </summary>
        /// <param name="value">The value to write</param>
366
        public void WriteSInt64(long value)
367 368 369 370
        {
            WriteRawVarint64(EncodeZigZag64(value));
        }

371 372 373 374 375 376 377 378 379 380 381 382
        /// <summary>
        /// Writes a length (in bytes) for length-delimited data.
        /// </summary>
        /// <remarks>
        /// This method simply writes a rawint, but exists for clarity in calling code.
        /// </remarks>
        /// <param name="length">Length value, in bytes.</param>
        public void WriteLength(int length)
        {
            WriteRawVarint32((uint) length);
        }

383 384
        #endregion

385 386 387 388
        #region Raw tag writing
        /// <summary>
        /// Encodes and writes a tag.
        /// </summary>
389 390
        /// <param name="fieldNumber">The number of the field to write the tag for</param>
        /// <param name="type">The wire format type of the tag to write</param>
391 392 393 394 395
        public void WriteTag(int fieldNumber, WireFormat.WireType type)
        {
            WriteRawVarint32(WireFormat.MakeTag(fieldNumber, type));
        }

Jon Skeet's avatar
Jon Skeet committed
396 397 398
        /// <summary>
        /// Writes an already-encoded tag.
        /// </summary>
399
        /// <param name="tag">The encoded tag</param>
Jon Skeet's avatar
Jon Skeet committed
400 401 402 403 404
        public void WriteTag(uint tag)
        {
            WriteRawVarint32(tag);
        }

405 406 407
        /// <summary>
        /// Writes the given single-byte tag directly to the stream.
        /// </summary>
408
        /// <param name="b1">The encoded tag</param>
409 410 411 412 413 414 415 416
        public void WriteRawTag(byte b1)
        {
            WriteRawByte(b1);
        }

        /// <summary>
        /// Writes the given two-byte tag directly to the stream.
        /// </summary>
417 418
        /// <param name="b1">The first byte of the encoded tag</param>
        /// <param name="b2">The second byte of the encoded tag</param>
419 420 421 422 423 424 425 426 427
        public void WriteRawTag(byte b1, byte b2)
        {
            WriteRawByte(b1);
            WriteRawByte(b2);
        }

        /// <summary>
        /// Writes the given three-byte tag directly to the stream.
        /// </summary>
428 429 430
        /// <param name="b1">The first byte of the encoded tag</param>
        /// <param name="b2">The second byte of the encoded tag</param>
        /// <param name="b3">The third byte of the encoded tag</param>
431 432 433 434 435 436 437 438 439 440
        public void WriteRawTag(byte b1, byte b2, byte b3)
        {
            WriteRawByte(b1);
            WriteRawByte(b2);
            WriteRawByte(b3);
        }

        /// <summary>
        /// Writes the given four-byte tag directly to the stream.
        /// </summary>
441 442 443 444
        /// <param name="b1">The first byte of the encoded tag</param>
        /// <param name="b2">The second byte of the encoded tag</param>
        /// <param name="b3">The third byte of the encoded tag</param>
        /// <param name="b4">The fourth byte of the encoded tag</param>
445 446 447 448 449 450 451 452 453 454 455
        public void WriteRawTag(byte b1, byte b2, byte b3, byte b4)
        {
            WriteRawByte(b1);
            WriteRawByte(b2);
            WriteRawByte(b3);
            WriteRawByte(b4);
        }

        /// <summary>
        /// Writes the given five-byte tag directly to the stream.
        /// </summary>
456 457 458 459 460
        /// <param name="b1">The first byte of the encoded tag</param>
        /// <param name="b2">The second byte of the encoded tag</param>
        /// <param name="b3">The third byte of the encoded tag</param>
        /// <param name="b4">The fourth byte of the encoded tag</param>
        /// <param name="b5">The fifth byte of the encoded tag</param>
461 462 463 464 465 466 467 468 469 470
        public void WriteRawTag(byte b1, byte b2, byte b3, byte b4, byte b5)
        {
            WriteRawByte(b1);
            WriteRawByte(b2);
            WriteRawByte(b3);
            WriteRawByte(b4);
            WriteRawByte(b5);
        }
        #endregion

471 472 473 474 475 476
        #region Underlying writing primitives
        /// <summary>
        /// Writes a 32 bit value as a varint. The fast route is taken when
        /// there's enough buffer space left to whizz through without checking
        /// for each byte; otherwise, we resort to calling WriteRawByte each time.
        /// </summary>
477
        internal void WriteRawVarint32(uint value)
478
        {
479 480 481 482 483 484 485
            // Optimize for the common case of a single byte value
            if (value < 128 && position < limit)
            {
                buffer[position++] = (byte)value;
                return;
            }

486 487
            while (value > 127 && position < limit)
            {
488
                buffer[position++] = (byte) ((value & 0x7F) | 0x80);
489 490 491 492
                value >>= 7;
            }
            while (value > 127)
            {
493
                WriteRawByte((byte) ((value & 0x7F) | 0x80));
494 495
                value >>= 7;
            }
496 497 498 499
            if (position < limit)
            {
                buffer[position++] = (byte) value;
            }
500
            else
501 502 503
            {
                WriteRawByte((byte) value);
            }
504 505
        }

506
        internal void WriteRawVarint64(ulong value)
507
        {
508 509
            while (value > 127 && position < limit)
            {
510
                buffer[position++] = (byte) ((value & 0x7F) | 0x80);
511 512 513 514
                value >>= 7;
            }
            while (value > 127)
            {
515
                WriteRawByte((byte) ((value & 0x7F) | 0x80));
516 517
                value >>= 7;
            }
518 519 520 521
            if (position < limit)
            {
                buffer[position++] = (byte) value;
            }
522
            else
523 524 525
            {
                WriteRawByte((byte) value);
            }
526 527
        }

528
        internal void WriteRawLittleEndian32(uint value)
529
        {
530 531 532 533 534 535 536 537 538
            if (position + 4 > limit)
            {
                WriteRawByte((byte) value);
                WriteRawByte((byte) (value >> 8));
                WriteRawByte((byte) (value >> 16));
                WriteRawByte((byte) (value >> 24));
            }
            else
            {
539 540 541 542
                buffer[position++] = ((byte) value);
                buffer[position++] = ((byte) (value >> 8));
                buffer[position++] = ((byte) (value >> 16));
                buffer[position++] = ((byte) (value >> 24));
543
            }
544 545
        }

546
        internal void WriteRawLittleEndian64(ulong value)
547
        {
548 549 550 551 552 553 554 555 556 557 558 559 560
            if (position + 8 > limit)
            {
                WriteRawByte((byte) value);
                WriteRawByte((byte) (value >> 8));
                WriteRawByte((byte) (value >> 16));
                WriteRawByte((byte) (value >> 24));
                WriteRawByte((byte) (value >> 32));
                WriteRawByte((byte) (value >> 40));
                WriteRawByte((byte) (value >> 48));
                WriteRawByte((byte) (value >> 56));
            }
            else
            {
561 562 563 564 565 566 567 568
                buffer[position++] = ((byte) value);
                buffer[position++] = ((byte) (value >> 8));
                buffer[position++] = ((byte) (value >> 16));
                buffer[position++] = ((byte) (value >> 24));
                buffer[position++] = ((byte) (value >> 32));
                buffer[position++] = ((byte) (value >> 40));
                buffer[position++] = ((byte) (value >> 48));
                buffer[position++] = ((byte) (value >> 56));
569
            }
570 571
        }

572
        internal void WriteRawByte(byte value)
573 574 575 576 577 578 579 580 581
        {
            if (position == limit)
            {
                RefreshBuffer();
            }

            buffer[position++] = value;
        }

582
        internal void WriteRawByte(uint value)
583 584 585 586 587 588 589
        {
            WriteRawByte((byte) value);
        }

        /// <summary>
        /// Writes out an array of bytes.
        /// </summary>
590
        internal void WriteRawBytes(byte[] value)
591 592 593 594 595 596 597
        {
            WriteRawBytes(value, 0, value.Length);
        }

        /// <summary>
        /// Writes out part of an array of bytes.
        /// </summary>
598
        internal void WriteRawBytes(byte[] value, int offset, int length)
599 600 601
        {
            if (limit - position >= length)
            {
602
                ByteArray.Copy(value, offset, buffer, position, length);
603 604 605 606 607 608 609 610
                // We have room in the current buffer.
                position += length;
            }
            else
            {
                // Write extends past current buffer.  Fill the rest of this buffer and
                // flush.
                int bytesWritten = limit - position;
611
                ByteArray.Copy(value, offset, buffer, position, bytesWritten);
612 613 614 615 616 617 618 619 620 621 622
                offset += bytesWritten;
                length -= bytesWritten;
                position = limit;
                RefreshBuffer();

                // Now deal with the rest.
                // Since we have an output stream, this is our buffer
                // and buffer offset == 0
                if (length <= limit)
                {
                    // Fits in new buffer.
623
                    ByteArray.Copy(value, offset, buffer, 0, length);
624 625 626 627 628 629 630 631 632 633 634
                    position = length;
                }
                else
                {
                    // Write is very big.  Let's do it all at once.
                    output.Write(value, offset, length);
                }
            }
        }

        #endregion
635

636 637 638 639 640 641 642 643 644
        /// <summary>
        /// Encode a 32-bit value with ZigZag encoding.
        /// </summary>
        /// <remarks>
        /// ZigZag encodes signed integers into values that can be efficiently
        /// encoded with varint.  (Otherwise, negative values must be 
        /// sign-extended to 64 bits to be varint encoded, thus always taking
        /// 10 bytes on the wire.)
        /// </remarks>
645
        internal static uint EncodeZigZag32(int n)
646 647 648 649 650 651 652 653 654 655 656 657 658 659
        {
            // Note:  the right-shift must be arithmetic
            return (uint) ((n << 1) ^ (n >> 31));
        }

        /// <summary>
        /// Encode a 64-bit value with ZigZag encoding.
        /// </summary>
        /// <remarks>
        /// ZigZag encodes signed integers into values that can be efficiently
        /// encoded with varint.  (Otherwise, negative values must be 
        /// sign-extended to 64 bits to be varint encoded, thus always taking
        /// 10 bytes on the wire.)
        /// </remarks>
660
        internal static ulong EncodeZigZag64(long n)
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
        {
            return (ulong) ((n << 1) ^ (n >> 63));
        }

        private void RefreshBuffer()
        {
            if (output == null)
            {
                // We're writing to a single buffer.
                throw new OutOfSpaceException();
            }

            // Since we have an output stream, this is our buffer
            // and buffer offset == 0
            output.Write(buffer, 0, position);
            position = 0;
        }

        /// <summary>
        /// Indicates that a CodedOutputStream wrapping a flat byte array
        /// ran out of space.
        /// </summary>
        public sealed class OutOfSpaceException : IOException
        {
            internal OutOfSpaceException()
                : base("CodedOutputStream was writing to a flat byte array and ran out of space.")
            {
            }
        }

691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
        /// <summary>
        /// Flushes any buffered data and optionally closes the underlying stream, if any.
        /// </summary>
        /// <remarks>
        /// <para>
        /// By default, any underlying stream is closed by this method. To configure this behaviour,
        /// use a constructor overload with a <c>leaveOpen</c> parameter. If this instance does not
        /// have an underlying stream, this method does nothing.
        /// </para>
        /// <para>
        /// For the sake of efficiency, calling this method does not prevent future write calls - but
        /// if a later write ends up writing to a stream which has been disposed, that is likely to
        /// fail. It is recommend that you not call any other methods after this.
        /// </para>
        /// </remarks>
        public void Dispose()
        {
            Flush();
            if (!leaveOpen)
            {
                output.Dispose();
            }
        }

715 716 717
        /// <summary>
        /// Flushes any buffered data to the underlying stream (if there is one).
        /// </summary>
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
        public void Flush()
        {
            if (output != null)
            {
                RefreshBuffer();
            }
        }

        /// <summary>
        /// Verifies that SpaceLeft returns zero. It's common to create a byte array
        /// that is exactly big enough to hold a message, then write to it with
        /// a CodedOutputStream. Calling CheckNoSpaceLeft after writing verifies that
        /// the message was actually as big as expected, which can help bugs.
        /// </summary>
        public void CheckNoSpaceLeft()
        {
            if (SpaceLeft != 0)
            {
                throw new InvalidOperationException("Did not write as much data as expected.");
            }
        }

        /// <summary>
        /// If writing to a flat array, returns the space left in the array. Otherwise,
        /// throws an InvalidOperationException.
        /// </summary>
        public int SpaceLeft
        {
            get
            {
                if (output == null)
                {
                    return limit - position;
                }
                else
                {
                    throw new InvalidOperationException(
                        "SpaceLeft can only be called on CodedOutputStreams that are " +
                        "writing to a flat array.");
                }
            }
        }
    }
761
}