CodedOutputStream.cs 30.8 KB
Newer Older
1 2 3 4 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 33 34 35 36 37 38 39
#region Copyright notice and license

// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc.  All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// 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

using System;
using System.IO;
using System.Text;
40
using Google.Protobuf.Collections;
41

42
namespace Google.Protobuf
43 44 45 46 47 48 49 50 51 52 53 54 55 56
{
    /// <summary>
    /// Encodes and writes protocol message fields.
    /// </summary>
    /// <remarks>
    /// This class contains two kinds of methods:  methods that write specific
    /// protocol message constructs and field types (e.g. WriteTag and
    /// WriteInt32) and methods that write low-level values (e.g.
    /// WriteRawVarint32 and WriteRawBytes).  If you are writing encoded protocol
    /// messages, you should use the former methods, but if you are writing some
    /// other format of your own design, use the latter. The names of the former
    /// methods are taken from the protocol buffer type names, not .NET types.
    /// (Hence WriteFloat instead of WriteSingle, and WriteBool instead of WriteBoolean.)
    /// </remarks>
Jon Skeet's avatar
Jon Skeet committed
57
    public sealed partial class CodedOutputStream
58
    {
59 60
        // "Local" copy of Encoding.UTF8, for efficiency. (Yes, it makes a difference.)
        internal static readonly Encoding Utf8Encoding = Encoding.UTF8;
61

62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
        /// <summary>
        /// The buffer size used by CreateInstance(Stream).
        /// </summary>
        public static readonly int DefaultBufferSize = 4096;

        private readonly byte[] buffer;
        private readonly int limit;
        private int position;
        private readonly Stream output;

        #region Construction

        private CodedOutputStream(byte[] buffer, int offset, int length)
        {
            this.output = null;
            this.buffer = buffer;
            this.position = offset;
            this.limit = offset + length;
        }

        private CodedOutputStream(Stream output, byte[] buffer)
        {
            this.output = output;
            this.buffer = buffer;
            this.position = 0;
            this.limit = buffer.Length;
        }

        /// <summary>
        /// Creates a new CodedOutputStream which write to the given stream.
        /// </summary>
        public static CodedOutputStream CreateInstance(Stream output)
        {
            return CreateInstance(output, DefaultBufferSize);
        }

        /// <summary>
        /// Creates a new CodedOutputStream which write to the given stream and uses
        /// the specified buffer size.
        /// </summary>
        public static CodedOutputStream CreateInstance(Stream output, int bufferSize)
        {
            return new CodedOutputStream(output, new byte[bufferSize]);
        }

        /// <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 static CodedOutputStream CreateInstance(byte[] flatArray)
        {
            return CreateInstance(flatArray, 0, flatArray.Length);
        }

        /// <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>
        public static CodedOutputStream CreateInstance(byte[] flatArray, int offset, int length)
        {
            return new CodedOutputStream(flatArray, offset, length);
        }

        #endregion
128 129 130 131 132 133 134 135 136

        /// <summary>
        /// Returns the current position in the stream, or the position in the output buffer
        /// </summary>
        public long Position
        {
            get
            {
                if (output != null)
137
                {
138
                    return output.Position + position;
139
                }
140 141 142 143
                return position;
            }
        }

144
        #region Writing of values without tags
145 146 147 148

        /// <summary>
        /// Writes a double field value, including tag, to the stream.
        /// </summary>
149
        public void WriteDouble(double value)
150
        {
Jon Skeet's avatar
Jon Skeet committed
151
            WriteRawLittleEndian64((ulong)BitConverter.DoubleToInt64Bits(value));
152 153 154 155 156
        }

        /// <summary>
        /// Writes a float field value, without a tag, to the stream.
        /// </summary>
157
        public void WriteFloat(float value)
158 159
        {
            byte[] rawBytes = BitConverter.GetBytes(value);
160
            if (!BitConverter.IsLittleEndian)
161
            {
162
                ByteArray.Reverse(rawBytes);
163
            }
164 165 166 167 168 169 170 171 172

            if (limit - position >= 4)
            {
                buffer[position++] = rawBytes[0];
                buffer[position++] = rawBytes[1];
                buffer[position++] = rawBytes[2];
                buffer[position++] = rawBytes[3];
            }
            else
173
            {
174
                WriteRawBytes(rawBytes, 0, 4);
175
            }
176 177 178 179 180
        }

        /// <summary>
        /// Writes a uint64 field value, without a tag, to the stream.
        /// </summary>
181
        public void WriteUInt64(ulong value)
182 183 184 185 186 187 188
        {
            WriteRawVarint64(value);
        }

        /// <summary>
        /// Writes an int64 field value, without a tag, to the stream.
        /// </summary>
189
        public void WriteInt64(long value)
190
        {
191
            WriteRawVarint64((ulong) value);
192 193 194 195 196
        }

        /// <summary>
        /// Writes an int32 field value, without a tag, to the stream.
        /// </summary>
197
        public void WriteInt32(int value)
198 199 200
        {
            if (value >= 0)
            {
201
                WriteRawVarint32((uint) value);
202 203 204 205
            }
            else
            {
                // Must sign-extend.
206
                WriteRawVarint64((ulong) value);
207 208 209 210 211 212
            }
        }

        /// <summary>
        /// Writes a fixed64 field value, without a tag, to the stream.
        /// </summary>
213
        public void WriteFixed64(ulong value)
214 215 216 217 218 219 220
        {
            WriteRawLittleEndian64(value);
        }

        /// <summary>
        /// Writes a fixed32 field value, without a tag, to the stream.
        /// </summary>
221
        public void WriteFixed32(uint value)
222 223 224 225 226 227 228
        {
            WriteRawLittleEndian32(value);
        }

        /// <summary>
        /// Writes a bool field value, without a tag, to the stream.
        /// </summary>
229
        public void WriteBool(bool value)
230
        {
231
            WriteRawByte(value ? (byte) 1 : (byte) 0);
232 233 234 235 236
        }

        /// <summary>
        /// Writes a string field value, without a tag, to the stream.
        /// </summary>
237
        public void WriteString(string value)
238 239 240
        {
            // Optimise the case where we have enough space to write
            // the string directly to the buffer, which should be common.
241
            int length = Utf8Encoding.GetByteCount(value);
242
            WriteRawVarint32((uint)length);
243 244
            if (limit - position >= length)
            {
245 246 247 248 249 250 251 252 253
                if (length == value.Length) // Must be all ASCII...
                {
                    for (int i = 0; i < length; i++)
                    {
                        buffer[position + i] = (byte)value[i];
                    }
                }
                else
                {
254
                    Utf8Encoding.GetBytes(value, 0, value.Length, buffer, position);
255
                }
256 257 258 259
                position += length;
            }
            else
            {
260
                byte[] bytes = Utf8Encoding.GetBytes(value);
261 262 263 264
                WriteRawBytes(bytes);
            }
        }

265
        public void WriteMessage(IMessage value)
266
        {
267
            WriteRawVarint32((uint) value.CalculateSize());
268 269 270
            value.WriteTo(this);
        }

271
        public void WriteBytes(ByteString value)
272
        {
273
            WriteRawVarint32((uint) value.Length);
274
            value.WriteRawBytesTo(this);
275 276
        }

277
        public void WriteUInt32(uint value)
278 279 280 281
        {
            WriteRawVarint32(value);
        }

282
        public void WriteEnum(int value)
283
        {
284
            WriteInt32(value);
285 286
        }

287
        public void WriteSFixed32(int value)
288
        {
289
            WriteRawLittleEndian32((uint) value);
290 291
        }

292
        public void WriteSFixed64(long value)
293
        {
294
            WriteRawLittleEndian64((ulong) value);
295 296
        }

297
        public void WriteSInt32(int value)
298 299 300 301
        {
            WriteRawVarint32(EncodeZigZag32(value));
        }

302
        public void WriteSInt64(long value)
303 304 305 306 307 308
        {
            WriteRawVarint64(EncodeZigZag64(value));
        }

        #endregion

309
        #region Write array members, with fields.
310
        public void WriteMessageArray<T>(int fieldNumber, RepeatedField<T> list)
311
            where T : IMessage
312
        {
313
            foreach (T value in list)
314
            {
315 316
                WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited);
                WriteMessage(value);
317
            }
318 319
        }

Jon Skeet's avatar
Jon Skeet committed
320
        public void WriteStringArray(int fieldNumber, RepeatedField<string> list)
321 322
        {
            foreach (var value in list)
323
            {
324 325
                WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited);
                WriteString(value);
326
            }
327 328
        }

Jon Skeet's avatar
Jon Skeet committed
329
        public void WriteBytesArray(int fieldNumber, RepeatedField<ByteString> list)
330 331
        {
            foreach (var value in list)
332
            {
333 334
                WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited);
                WriteBytes(value);
335
            }
336 337
        }

Jon Skeet's avatar
Jon Skeet committed
338
        public void WriteBoolArray(int fieldNumber, RepeatedField<bool> list)
339 340
        {
            foreach (var value in list)
341
            {
342 343
                WriteTag(fieldNumber, WireFormat.WireType.Varint);
                WriteBool(value);
344
            }
345 346
        }

Jon Skeet's avatar
Jon Skeet committed
347
        public void WriteInt32Array(int fieldNumber, RepeatedField<int> list)
348 349
        {
            foreach (var value in list)
350
            {
351 352
                WriteTag(fieldNumber, WireFormat.WireType.Varint);
                WriteInt32(value);
353
            }
354 355
        }

Jon Skeet's avatar
Jon Skeet committed
356
        public void WriteSInt32Array(int fieldNumber, RepeatedField<int> list)
357 358
        {
            foreach (var value in list)
359
            {
360 361
                WriteTag(fieldNumber, WireFormat.WireType.Varint);
                WriteSInt32(value);
362
            }
363 364
        }

Jon Skeet's avatar
Jon Skeet committed
365
        public void WriteUInt32Array(int fieldNumber, RepeatedField<uint> list)
366 367
        {
            foreach (var value in list)
368
            {
369 370
                WriteTag(fieldNumber, WireFormat.WireType.Varint);
                WriteUInt32(value);
371
            }
372 373
        }

Jon Skeet's avatar
Jon Skeet committed
374
        public void WriteFixed32Array(int fieldNumber, RepeatedField<uint> list)
375 376
        {
            foreach (var value in list)
377
            {
378 379
                WriteTag(fieldNumber, WireFormat.WireType.Fixed32);
                WriteFixed32(value);
380
            }
381 382
        }

Jon Skeet's avatar
Jon Skeet committed
383
        public void WriteSFixed32Array(int fieldNumber, RepeatedField<int> list)
384 385
        {
            foreach (var value in list)
386
            {
387 388
                WriteTag(fieldNumber, WireFormat.WireType.Fixed32);
                WriteSFixed32(value);
389
            }
390 391
        }

Jon Skeet's avatar
Jon Skeet committed
392
        public void WriteInt64Array(int fieldNumber, RepeatedField<long> list)
393 394
        {
            foreach (var value in list)
395
            {
396 397
                WriteTag(fieldNumber, WireFormat.WireType.Fixed64);
                WriteInt64(value);
398
            }
399 400
        }

Jon Skeet's avatar
Jon Skeet committed
401
        public void WriteSInt64Array(int fieldNumber, RepeatedField<long> list)
402 403
        {
            foreach (var value in list)
404
            {
405 406
                WriteTag(fieldNumber, WireFormat.WireType.Varint);
                WriteSInt64(value);
407
            }
408 409
        }

Jon Skeet's avatar
Jon Skeet committed
410
        public void WriteUInt64Array(int fieldNumber, RepeatedField<ulong> list)
411 412
        {
            foreach (var value in list)
413
            {
414 415
                WriteTag(fieldNumber, WireFormat.WireType.Varint);
                WriteUInt64(value);
416
            }
417 418
        }

Jon Skeet's avatar
Jon Skeet committed
419
        public void WriteFixed64Array(int fieldNumber, RepeatedField<ulong> list)
420 421
        {
            foreach (var value in list)
422
            {
423 424
                WriteTag(fieldNumber, WireFormat.WireType.Fixed64);
                WriteFixed64(value);
425
            }
426 427
        }

Jon Skeet's avatar
Jon Skeet committed
428
        public void WriteSFixed64Array(int fieldNumber, RepeatedField<long> list)
429 430
        {
            foreach (var value in list)
431
            {
432 433
                WriteTag(fieldNumber, WireFormat.WireType.Fixed64);
                WriteSFixed64(value);
434
            }
435 436
        }

Jon Skeet's avatar
Jon Skeet committed
437
        public void WriteDoubleArray(int fieldNumber, RepeatedField<double> list)
438 439
        {
            foreach (var value in list)
440
            {
441 442
                WriteTag(fieldNumber, WireFormat.WireType.Fixed64);
                WriteDouble(value);
443
            }
444 445
        }

Jon Skeet's avatar
Jon Skeet committed
446
        public void WriteFloatArray(int fieldNumber, RepeatedField<float> list)
447 448
        {
            foreach (var value in list)
449
            {
450 451
                WriteTag(fieldNumber, WireFormat.WireType.Fixed32);
                WriteFloat(value);
452
            }
453 454
        }

Jon Skeet's avatar
Jon Skeet committed
455
        public void WriteEnumArray<T>(int fieldNumber, RepeatedField<T> list)
csharptest's avatar
csharptest committed
456
            where T : struct, IComparable, IFormattable
457
        {
458 459 460
            // Bit of a hack, to access the values as ints
            var iterator = list.GetInt32Enumerator();
            while (iterator.MoveNext())
461
            {
462 463
                WriteTag(fieldNumber, WireFormat.WireType.Varint);
                WriteEnum(iterator.Current);
464 465 466 467 468
            }
        }

        #endregion

469 470 471 472 473 474 475 476 477
        #region Raw tag writing
        /// <summary>
        /// Encodes and writes a tag.
        /// </summary>
        public void WriteTag(int fieldNumber, WireFormat.WireType type)
        {
            WriteRawVarint32(WireFormat.MakeTag(fieldNumber, type));
        }

Jon Skeet's avatar
Jon Skeet committed
478 479 480 481 482 483 484 485
        /// <summary>
        /// Writes an already-encoded tag.
        /// </summary>
        public void WriteTag(uint tag)
        {
            WriteRawVarint32(tag);
        }

486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
        /// <summary>
        /// Writes the given single-byte tag directly to the stream.
        /// </summary>
        public void WriteRawTag(byte b1)
        {
            WriteRawByte(b1);
        }

        /// <summary>
        /// Writes the given two-byte tag directly to the stream.
        /// </summary>
        public void WriteRawTag(byte b1, byte b2)
        {
            WriteRawByte(b1);
            WriteRawByte(b2);
        }

        /// <summary>
        /// Writes the given three-byte tag directly to the stream.
        /// </summary>
        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>
        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>
        public void WriteRawTag(byte b1, byte b2, byte b3, byte b4, byte b5)
        {
            WriteRawByte(b1);
            WriteRawByte(b2);
            WriteRawByte(b3);
            WriteRawByte(b4);
            WriteRawByte(b5);
        }
        #endregion

537
        #region Write packed array members
538
        // TODO(jonskeet): A lot of these are really inefficient, due to method group conversions. Fix!
539 540
        // (Alternatively, add extension methods to RepeatedField, accepting the Write* methods via delegates too.)
        public void WritePackedBoolArray(RepeatedField<bool> list)
541
        {
542 543
            uint size = (uint)list.Count;
            WriteRawVarint32(size);
544
            foreach (var value in list)
545
            {
546
                WriteBool(value);
547
            }
548 549
        }

550
        public void WritePackedInt32Array(RepeatedField<int> list)
551
        {
552
            uint size = list.CalculateSize(ComputeInt32Size);
553
            WriteRawVarint32(size);
554
            foreach (var value in list)
555
            {
556
                WriteInt32(value);
557
            }
558 559
        }

560
        public void WritePackedSInt32Array(RepeatedField<int> list)
561
        {
562
            uint size = list.CalculateSize(ComputeSInt32Size);
563
            WriteRawVarint32(size);
564
            foreach (var value in list)
565
            {
566
                WriteSInt32(value);
567
            }
568 569
        }

570
        public void WritePackedUInt32Array(RepeatedField<uint> list)
571
        {
572
            uint size = list.CalculateSize(ComputeUInt32Size);
573
            WriteRawVarint32(size);
574
            foreach (var value in list)
575
            {
576
                WriteUInt32(value);
577
            }
578 579
        }

580
        public void WritePackedFixed32Array(RepeatedField<uint> list)
581
        {
582 583
            uint size = (uint) list.Count * 4;
            WriteRawVarint32(size);
584
            foreach (var value in list)
585
            {
586
                WriteFixed32(value);
587
            }
588 589
        }

590
        public void WritePackedSFixed32Array(RepeatedField<int> list)
591
        {
592 593
            uint size = (uint) list.Count * 4;
            WriteRawVarint32(size);
594
            foreach (var value in list)
595
            {
596
                WriteSFixed32(value);
597
            }
598 599
        }

600
        public void WritePackedInt64Array(RepeatedField<long> list)
601
        {
602
            uint size = list.CalculateSize(ComputeInt64Size);
603
            WriteRawVarint32(size);
604
            foreach (var value in list)
605
            {
606
                WriteInt64(value);
607
            }
608 609
        }

610
        public void WritePackedSInt64Array(RepeatedField<long> list)
611
        {
612
            uint size = list.CalculateSize(ComputeSInt64Size);
613
            WriteRawVarint32(size);
614
            foreach (var value in list)
615
            {
616
                WriteSInt64(value);
617
            }
618 619
        }

620
        public void WritePackedUInt64Array(RepeatedField<ulong> list)
621
        {
622 623 624 625
            if (list.Count == 0)
            {
                return;
            }
626
            uint size = list.CalculateSize(ComputeUInt64Size);
627
            WriteRawVarint32(size);
628
            foreach (var value in list)
629
            {
630
                WriteUInt64(value);
631
            }
632 633
        }

634
        public void WritePackedFixed64Array(RepeatedField<ulong> list)
635
        {
636 637
            uint size = (uint) list.Count * 8;
            WriteRawVarint32(size);
638
            foreach (var value in list)
639
            {
640
                WriteFixed64(value);
641
            }
642 643
        }

644
        public void WritePackedSFixed64Array(RepeatedField<long> list)
645
        {
646 647
            uint size = (uint) list.Count * 8;
            WriteRawVarint32(size);
648
            foreach (var value in list)
649
            {
650
                WriteSFixed64(value);
651
            }
652 653
        }

654
        public void WritePackedDoubleArray(RepeatedField<double> list)
655
        {
656 657
            uint size = (uint) list.Count * 8;
            WriteRawVarint32(size);
658
            foreach (var value in list)
659
            {
660
                WriteDouble(value);
661
            }
662 663
        }

664
        public void WritePackedFloatArray(RepeatedField<float> list)
665
        {
666 667 668 669 670 671
            if (list.Count == 0)
            {
                return;
            }
            uint size = (uint) list.Count * 4;
            WriteRawVarint32(size);
672
            foreach (var value in list)
673
            {
674
                WriteFloat(value);
675
            }
676 677
        }

678
        public void WritePackedEnumArray<T>(RepeatedField<T> list)
csharptest's avatar
csharptest committed
679
            where T : struct, IComparable, IFormattable
680
        {
681
            if (list.Count == 0)
682
            {
683
                return;
684
            }
685 686 687 688 689
            // Bit of a hack, to access the values as ints
            var iterator = list.GetInt32Enumerator();
            uint size = 0;
            while (iterator.MoveNext())
            {
690
                size += (uint) ComputeEnumSize(iterator.Current);
691 692
            }
            iterator.Reset();
693
            WriteRawVarint32(size);
694
            while (iterator.MoveNext())
695
            {
696
                WriteEnum(iterator.Current);
697 698 699 700 701
            }
        }

        #endregion

702 703 704 705 706 707 708 709
        #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>
        public void WriteRawVarint32(uint value)
        {
710 711 712 713 714 715 716
            // Optimize for the common case of a single byte value
            if (value < 128 && position < limit)
            {
                buffer[position++] = (byte)value;
                return;
            }

717 718
            while (value > 127 && position < limit)
            {
719
                buffer[position++] = (byte) ((value & 0x7F) | 0x80);
720 721 722 723
                value >>= 7;
            }
            while (value > 127)
            {
724
                WriteRawByte((byte) ((value & 0x7F) | 0x80));
725 726
                value >>= 7;
            }
727 728 729 730
            if (position < limit)
            {
                buffer[position++] = (byte) value;
            }
731
            else
732 733 734
            {
                WriteRawByte((byte) value);
            }
735 736 737 738
        }

        public void WriteRawVarint64(ulong value)
        {
739 740
            while (value > 127 && position < limit)
            {
741
                buffer[position++] = (byte) ((value & 0x7F) | 0x80);
742 743 744 745
                value >>= 7;
            }
            while (value > 127)
            {
746
                WriteRawByte((byte) ((value & 0x7F) | 0x80));
747 748
                value >>= 7;
            }
749 750 751 752
            if (position < limit)
            {
                buffer[position++] = (byte) value;
            }
753
            else
754 755 756
            {
                WriteRawByte((byte) value);
            }
757 758 759 760
        }

        public void WriteRawLittleEndian32(uint value)
        {
761 762 763 764 765 766 767 768 769
            if (position + 4 > limit)
            {
                WriteRawByte((byte) value);
                WriteRawByte((byte) (value >> 8));
                WriteRawByte((byte) (value >> 16));
                WriteRawByte((byte) (value >> 24));
            }
            else
            {
770 771 772 773
                buffer[position++] = ((byte) value);
                buffer[position++] = ((byte) (value >> 8));
                buffer[position++] = ((byte) (value >> 16));
                buffer[position++] = ((byte) (value >> 24));
774
            }
775 776 777 778
        }

        public void WriteRawLittleEndian64(ulong value)
        {
779 780 781 782 783 784 785 786 787 788 789 790 791
            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
            {
792 793 794 795 796 797 798 799
                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));
800
            }
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
        }

        public void WriteRawByte(byte value)
        {
            if (position == limit)
            {
                RefreshBuffer();
            }

            buffer[position++] = value;
        }

        public void WriteRawByte(uint value)
        {
            WriteRawByte((byte) value);
        }

        /// <summary>
        /// Writes out an array of bytes.
        /// </summary>
        public void WriteRawBytes(byte[] value)
        {
            WriteRawBytes(value, 0, value.Length);
        }

        /// <summary>
        /// Writes out part of an array of bytes.
        /// </summary>
        public void WriteRawBytes(byte[] value, int offset, int length)
        {
            if (limit - position >= length)
            {
833
                ByteArray.Copy(value, offset, buffer, position, length);
834 835 836 837 838 839 840 841
                // 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;
842
                ByteArray.Copy(value, offset, buffer, position, bytesWritten);
843 844 845 846 847 848 849 850 851 852 853
                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.
854
                    ByteArray.Copy(value, offset, buffer, 0, length);
855 856 857 858 859 860 861 862 863 864 865
                    position = length;
                }
                else
                {
                    // Write is very big.  Let's do it all at once.
                    output.Write(value, offset, length);
                }
            }
        }

        #endregion
866

867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
        /// <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>
        public static uint EncodeZigZag32(int n)
        {
            // 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>
        public static ulong EncodeZigZag64(long n)
        {
            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.")
            {
            }
        }

        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.");
                }
            }
        }
    }
}