UnknownFieldSet.cs 41.6 KB
Newer Older
csharptest's avatar
csharptest committed
1
#region Copyright notice and license
2

csharptest's avatar
csharptest committed
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
// 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.
34

csharptest's avatar
csharptest committed
35 36 37 38 39 40 41 42
#endregion

using System;
using System.Collections.Generic;
using System.IO;
using Google.ProtocolBuffers.Collections;
using Google.ProtocolBuffers.Descriptors;

43 44
namespace Google.ProtocolBuffers
{
csharptest's avatar
csharptest committed
45
    /// <summary>
46 47 48 49 50 51 52 53 54
    /// Used to keep track of fields which were seen when parsing a protocol message
    /// but whose field numbers or types are unrecognized. This most frequently
    /// occurs when new fields are added to a message type and then messages containing
    /// those fields are read by old software that was built before the new types were
    /// added.
    /// 
    /// Every message contains an UnknownFieldSet.
    /// 
    /// Most users will never need to use this class directly.
csharptest's avatar
csharptest committed
55
    /// </summary>
56
    public sealed partial class UnknownFieldSet : IMessageLite
57 58 59
    {
        private static readonly UnknownFieldSet defaultInstance =
            new UnknownFieldSet(new Dictionary<int, UnknownField>());
csharptest's avatar
csharptest committed
60

61
        private readonly IDictionary<int, UnknownField> fields;
csharptest's avatar
csharptest committed
62

63 64 65
        private UnknownFieldSet(IDictionary<int, UnknownField> fields)
        {
            this.fields = fields;
csharptest's avatar
csharptest committed
66 67
        }

68 69 70 71 72 73 74
        /// <summary>
        /// Creates a new unknown field set builder.
        /// </summary>
        public static Builder CreateBuilder()
        {
            return new Builder();
        }
csharptest's avatar
csharptest committed
75

76 77 78 79 80 81 82
        /// <summary>
        /// Creates a new unknown field set builder 
        /// and initialize it from <paramref name="original"/>.
        /// </summary>
        public static Builder CreateBuilder(UnknownFieldSet original)
        {
            return new Builder().MergeFrom(original);
csharptest's avatar
csharptest committed
83 84
        }

85 86 87 88
        public static UnknownFieldSet DefaultInstance
        {
            get { return defaultInstance; }
        }
csharptest's avatar
csharptest committed
89

90 91 92 93 94 95 96
        /// <summary>
        /// Returns a read-only view of the mapping from field numbers to values.
        /// </summary>
        public IDictionary<int, UnknownField> FieldDictionary
        {
            get { return Dictionaries.AsReadOnly(fields); }
        }
csharptest's avatar
csharptest committed
97

98 99 100 101 102 103 104
        /// <summary>
        /// Checks whether or not the given field number is present in the set.
        /// </summary>
        public bool HasField(int field)
        {
            return fields.ContainsKey(field);
        }
csharptest's avatar
csharptest committed
105

106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
        /// <summary>
        /// Fetches a field by number, returning an empty field if not present.
        /// Never returns null.
        /// </summary>
        public UnknownField this[int number]
        {
            get
            {
                UnknownField ret;
                if (!fields.TryGetValue(number, out ret))
                {
                    ret = UnknownField.DefaultInstance;
                }
                return ret;
            }
        }
csharptest's avatar
csharptest committed
122

123 124 125
        /// <summary>
        /// Serializes the set and writes it to <paramref name="output"/>.
        /// </summary>
126
        public void WriteTo(ICodedOutputStream output)
127
        {
128 129
            // Avoid creating enumerator for the most common code path.
            if (fields.Count > 0)
130
            {
131 132 133 134
                foreach (KeyValuePair<int, UnknownField> entry in fields)
                {
                    entry.Value.WriteTo(entry.Key, output);
                }
135 136
            }
        }
csharptest's avatar
csharptest committed
137

138 139 140 141 142 143 144
        /// <summary>
        /// Gets the number of bytes required to encode this set.
        /// </summary>
        public int SerializedSize
        {
            get
            {
145 146 147 148 149 150
                // Avoid creating enumerator for the most common code path.
                if (fields.Count == 0)
                {
                    return 0;
                }

151 152 153 154 155 156 157 158
                int result = 0;
                foreach (KeyValuePair<int, UnknownField> entry in fields)
                {
                    result += entry.Value.GetSerializedSize(entry.Key);
                }
                return result;
            }
        }
csharptest's avatar
csharptest committed
159

160 161 162 163 164 165 166
        /// <summary>
        /// Converts the set to a string in protocol buffer text format. This
        /// is just a trivial wrapper around TextFormat.PrintToString.
        /// </summary>
        public override String ToString()
        {
            return TextFormat.PrintToString(this);
csharptest's avatar
csharptest committed
167 168
        }

169 170 171 172 173 174 175 176
        /// <summary>
        /// Converts the set to a string in protocol buffer text format. This
        /// is just a trivial wrapper around TextFormat.PrintToString.
        /// </summary>
        public void PrintTo(TextWriter writer)
        {
            TextFormat.Print(this, writer);
        }
csharptest's avatar
csharptest committed
177

178 179
        /// <summary>
        /// Serializes the message to a ByteString and returns it. This is
180
        /// just a trivial wrapper around WriteTo(ICodedOutputStream).
181 182 183 184 185 186 187 188
        /// </summary>
        /// <returns></returns>
        public ByteString ToByteString()
        {
            ByteString.CodedBuilder codedBuilder = new ByteString.CodedBuilder(SerializedSize);
            WriteTo(codedBuilder.CodedOutput);
            return codedBuilder.Build();
        }
csharptest's avatar
csharptest committed
189

190 191
        /// <summary>
        /// Serializes the message to a byte array and returns it. This is
192
        /// just a trivial wrapper around WriteTo(ICodedOutputStream).
193 194 195 196 197 198 199 200 201 202
        /// </summary>
        /// <returns></returns>
        public byte[] ToByteArray()
        {
            byte[] data = new byte[SerializedSize];
            CodedOutputStream output = CodedOutputStream.CreateInstance(data);
            WriteTo(output);
            output.CheckNoSpaceLeft();
            return data;
        }
csharptest's avatar
csharptest committed
203

204 205
        /// <summary>
        /// Serializes the message and writes it to <paramref name="output"/>. This is
206
        /// just a trivial wrapper around WriteTo(ICodedOutputStream).
207 208 209 210 211 212 213 214
        /// </summary>
        /// <param name="output"></param>
        public void WriteTo(Stream output)
        {
            CodedOutputStream codedOutput = CodedOutputStream.CreateInstance(output);
            WriteTo(codedOutput);
            codedOutput.Flush();
        }
csharptest's avatar
csharptest committed
215

216 217 218 219
        /// <summary>
        /// Serializes the set and writes it to <paramref name="output"/> using
        /// the MessageSet wire format.
        /// </summary>
220
        public void WriteAsMessageSetTo(ICodedOutputStream output)
221
        {
222 223
            // Avoid creating enumerator for the most common code path.
            if (fields.Count > 0)
224
            {
225 226 227 228
                foreach (KeyValuePair<int, UnknownField> entry in fields)
                {
                    entry.Value.WriteAsMessageSetExtensionTo(entry.Key, output);
                }
229 230
            }
        }
csharptest's avatar
csharptest committed
231

232 233 234 235 236 237 238 239
        /// <summary>
        /// Gets the number of bytes required to encode this set using the MessageSet
        /// wire format.
        /// </summary>
        public int SerializedSizeAsMessageSet
        {
            get
            {
240 241 242 243 244 245
                // Avoid creating enumerator for the most common code path.
                if (fields.Count == 0)
                {
                    return 0;
                }

246 247 248 249 250 251 252 253
                int result = 0;
                foreach (KeyValuePair<int, UnknownField> entry in fields)
                {
                    result += entry.Value.GetSerializedSizeAsMessageSetExtension(entry.Key);
                }
                return result;
            }
        }
csharptest's avatar
csharptest committed
254

255 256 257 258 259 260 261 262 263
        public override bool Equals(object other)
        {
            if (ReferenceEquals(this, other))
            {
                return true;
            }
            UnknownFieldSet otherSet = other as UnknownFieldSet;
            return otherSet != null && Dictionaries.Equals(fields, otherSet.fields);
        }
csharptest's avatar
csharptest committed
264

265 266 267 268
        public override int GetHashCode()
        {
            return Dictionaries.GetHashCode(fields);
        }
csharptest's avatar
csharptest committed
269

270 271 272
        /// <summary>
        /// Parses an UnknownFieldSet from the given input.
        /// </summary>
273
        public static UnknownFieldSet ParseFrom(ICodedInputStream input)
274 275 276
        {
            return CreateBuilder().MergeFrom(input).Build();
        }
csharptest's avatar
csharptest committed
277

278 279 280 281 282 283 284
        /// <summary>
        /// Parses an UnknownFieldSet from the given data.
        /// </summary>
        public static UnknownFieldSet ParseFrom(ByteString data)
        {
            return CreateBuilder().MergeFrom(data).Build();
        }
csharptest's avatar
csharptest committed
285

286 287 288 289 290 291 292
        /// <summary>
        /// Parses an UnknownFieldSet from the given data.
        /// </summary>
        public static UnknownFieldSet ParseFrom(byte[] data)
        {
            return CreateBuilder().MergeFrom(data).Build();
        }
csharptest's avatar
csharptest committed
293

294 295 296 297 298 299 300
        /// <summary>
        /// Parses an UnknownFieldSet from the given input.
        /// </summary>
        public static UnknownFieldSet ParseFrom(Stream input)
        {
            return CreateBuilder().MergeFrom(input).Build();
        }
csharptest's avatar
csharptest committed
301

302
        #region IMessageLite Members
csharptest's avatar
csharptest committed
303

304 305 306
        public bool IsInitialized
        {
            get { return fields != null; }
csharptest's avatar
csharptest committed
307 308
        }

309 310 311 312 313 314
        public void WriteDelimitedTo(Stream output)
        {
            CodedOutputStream codedOutput = CodedOutputStream.CreateInstance(output);
            codedOutput.WriteRawVarint32((uint) SerializedSize);
            WriteTo(codedOutput);
            codedOutput.Flush();
csharptest's avatar
csharptest committed
315
        }
316 317 318 319

        public IBuilderLite WeakCreateBuilderForType()
        {
            return new Builder();
csharptest's avatar
csharptest committed
320
        }
321 322 323 324

        public IBuilderLite WeakToBuilder()
        {
            return new Builder(fields);
csharptest's avatar
csharptest committed
325
        }
326 327 328 329

        public IMessageLite WeakDefaultInstanceForType
        {
            get { return defaultInstance; }
csharptest's avatar
csharptest committed
330
        }
331 332

        #endregion
csharptest's avatar
csharptest committed
333 334

        /// <summary>
335
        /// Builder for UnknownFieldSets.
csharptest's avatar
csharptest committed
336
        /// </summary>
337
        public sealed partial class Builder : IBuilderLite
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
        {
            /// <summary>
            /// Mapping from number to field. Note that by using a SortedList we ensure
            /// that the fields will be serialized in ascending order.
            /// </summary>
            private IDictionary<int, UnknownField> fields;

            // Optimization:  We keep around a builder for the last field that was
            // modified so that we can efficiently add to it multiple times in a
            // row (important when parsing an unknown repeated field).
            private int lastFieldNumber;
            private UnknownField.Builder lastField;

            internal Builder()
            {
353
                fields = new SortedDictionary<int, UnknownField>();
354 355 356 357
            }

            internal Builder(IDictionary<int, UnknownField> dictionary)
            {
358
                fields = new SortedDictionary<int, UnknownField>(dictionary);
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
            }

            /// <summary>
            /// Returns a field builder for the specified field number, including any values
            /// which already exist.
            /// </summary>
            private UnknownField.Builder GetFieldBuilder(int number)
            {
                if (lastField != null)
                {
                    if (number == lastFieldNumber)
                    {
                        return lastField;
                    }
                    // Note: AddField() will reset lastField and lastFieldNumber.
                    AddField(lastFieldNumber, lastField.Build());
                }
                if (number == 0)
                {
                    return null;
                }

                lastField = UnknownField.CreateBuilder();
                UnknownField existing;
                if (fields.TryGetValue(number, out existing))
                {
                    lastField.MergeFrom(existing);
                }
                lastFieldNumber = number;
                return lastField;
            }

            /// <summary>
            /// Build the UnknownFieldSet and return it. Once this method has been called,
            /// this instance will no longer be usable. Calling any method after this
            /// will throw a NullReferenceException.
            /// </summary>
            public UnknownFieldSet Build()
            {
                GetFieldBuilder(0); // Force lastField to be built.
                UnknownFieldSet result = fields.Count == 0 ? DefaultInstance : new UnknownFieldSet(fields);
                fields = null;
                return result;
            }

            /// <summary>
            /// Adds a field to the set. If a field with the same number already exists, it
            /// is replaced.
            /// </summary>
            public Builder AddField(int number, UnknownField field)
            {
                if (number == 0)
                {
                    throw new ArgumentOutOfRangeException("number", "Zero is not a valid field number.");
                }
                if (lastField != null && lastFieldNumber == number)
                {
                    // Discard this.
                    lastField = null;
                    lastFieldNumber = 0;
                }
                fields[number] = field;
                return this;
            }

            /// <summary>
            /// Resets the builder to an empty set.
            /// </summary>
            public Builder Clear()
            {
                fields.Clear();
                lastFieldNumber = 0;
                lastField = null;
                return this;
            }

            /// <summary>
            /// Parse an entire message from <paramref name="input"/> and merge
            /// its fields into this set.
            /// </summary>
439
            public Builder MergeFrom(ICodedInputStream input)
440
            {
441 442 443
                uint tag;
                string name;
                while (input.ReadTag(out tag, out name))
444
                {
445
                    if (tag == 0)
446
                    {
447
                        if (input.SkipField())
448
                        {
449
                            continue; //can't merge unknown without field tag
450
                        }
451 452
                        break;
                    }
453

454 455
                    if (!MergeFieldFrom(tag, input))
                    {
456
                        break;
457
                    }
458 459 460 461 462 463 464 465 466 467 468
                }
                return this;
            }

            /// <summary>
            /// Parse a single field from <paramref name="input"/> and merge it
            /// into this set.
            /// </summary>
            /// <param name="tag">The field's tag number, which was already parsed.</param>
            /// <param name="input">The coded input stream containing the field</param>
            /// <returns>false if the tag is an "end group" tag, true otherwise</returns>
469
            public bool MergeFieldFrom(uint tag, ICodedInputStream input)
470
            {
471 472 473 474 475 476
                if (tag == 0)
                {
                    input.SkipField();
                    return true;
                }

477 478 479 480
                int number = WireFormat.GetTagFieldNumber(tag);
                switch (WireFormat.GetTagWireType(tag))
                {
                    case WireFormat.WireType.Varint:
481 482
                        {
                            ulong uint64 = 0;
483 484
                            if (input.ReadUInt64(ref uint64))
                            {
485
                                GetFieldBuilder(number).AddVarint(uint64);
486
                            }
487 488 489 490 491 492
                            return true;
                        }
                    case WireFormat.WireType.Fixed32:
                        {
                            uint uint32 = 0;
                            if (input.ReadFixed32(ref uint32))
493
                            {
494
                                GetFieldBuilder(number).AddFixed32(uint32);
495
                            }
496 497
                            return true;
                        }
498
                    case WireFormat.WireType.Fixed64:
499 500 501
                        {
                            ulong uint64 = 0;
                            if (input.ReadFixed64(ref uint64))
502
                            {
503
                                GetFieldBuilder(number).AddFixed64(uint64);
504
                            }
505 506
                            return true;
                        }
507
                    case WireFormat.WireType.LengthDelimited:
508 509 510
                        {
                            ByteString bytes = null;
                            if (input.ReadBytes(ref bytes))
511
                            {
512
                                GetFieldBuilder(number).AddLengthDelimited(bytes);
513
                            }
514 515
                            return true;
                        }
516 517 518
                    case WireFormat.WireType.StartGroup:
                        {
                            Builder subBuilder = CreateBuilder();
csharptest's avatar
csharptest committed
519
#pragma warning disable 0612
520
                            input.ReadUnknownGroup(number, subBuilder);
csharptest's avatar
csharptest committed
521
#pragma warning restore 0612
522 523 524 525 526 527 528 529 530
                            GetFieldBuilder(number).AddGroup(subBuilder.Build());
                            return true;
                        }
                    case WireFormat.WireType.EndGroup:
                        return false;
                    default:
                        throw InvalidProtocolBufferException.InvalidWireType();
                }
            }
csharptest's avatar
csharptest committed
531

532 533 534
            /// <summary>
            /// Parses <paramref name="input"/> as an UnknownFieldSet and merge it
            /// with the set being built. This is just a small wrapper around
535
            /// MergeFrom(ICodedInputStream).
536 537 538 539 540 541 542 543
            /// </summary>
            public Builder MergeFrom(Stream input)
            {
                CodedInputStream codedInput = CodedInputStream.CreateInstance(input);
                MergeFrom(codedInput);
                codedInput.CheckLastTagWas(0);
                return this;
            }
csharptest's avatar
csharptest committed
544

545 546 547
            /// <summary>
            /// Parses <paramref name="data"/> as an UnknownFieldSet and merge it
            /// with the set being built. This is just a small wrapper around
548
            /// MergeFrom(ICodedInputStream).
549 550 551 552 553 554 555 556
            /// </summary>
            public Builder MergeFrom(ByteString data)
            {
                CodedInputStream input = data.CreateCodedInput();
                MergeFrom(input);
                input.CheckLastTagWas(0);
                return this;
            }
csharptest's avatar
csharptest committed
557

558 559 560
            /// <summary>
            /// Parses <paramref name="data"/> as an UnknownFieldSet and merge it
            /// with the set being built. This is just a small wrapper around
561
            /// MergeFrom(ICodedInputStream).
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
            /// </summary>
            public Builder MergeFrom(byte[] data)
            {
                CodedInputStream input = CodedInputStream.CreateInstance(data);
                MergeFrom(input);
                input.CheckLastTagWas(0);
                return this;
            }

            /// <summary>
            /// Convenience method for merging a new field containing a single varint
            /// value.  This is used in particular when an unknown enum value is
            /// encountered.
            /// </summary>
            public Builder MergeVarintField(int number, ulong value)
            {
                if (number == 0)
                {
                    throw new ArgumentOutOfRangeException("number", "Zero is not a valid field number.");
csharptest's avatar
csharptest committed
581
                }
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
                GetFieldBuilder(number).AddVarint(value);
                return this;
            }

            /// <summary>
            /// Merges the fields from <paramref name="other"/> into this set.
            /// If a field number exists in both sets, the values in <paramref name="other"/>
            /// will be appended to the values in this set.
            /// </summary>
            public Builder MergeFrom(UnknownFieldSet other)
            {
                if (other != DefaultInstance)
                {
                    foreach (KeyValuePair<int, UnknownField> entry in other.fields)
                    {
                        MergeField(entry.Key, entry.Value);
                    }
csharptest's avatar
csharptest committed
599
                }
600 601 602 603 604 605 606 607 608 609 610
                return this;
            }

            /// <summary>
            /// Checks if the given field number is present in the set.
            /// </summary>
            public bool HasField(int number)
            {
                if (number == 0)
                {
                    throw new ArgumentOutOfRangeException("number", "Zero is not a valid field number.");
csharptest's avatar
csharptest committed
611
                }
612 613 614 615 616 617 618 619 620 621 622 623
                return number == lastFieldNumber || fields.ContainsKey(number);
            }

            /// <summary>
            /// Adds a field to the unknown field set. If a field with the same
            /// number already exists, the two are merged.
            /// </summary>
            public Builder MergeField(int number, UnknownField field)
            {
                if (number == 0)
                {
                    throw new ArgumentOutOfRangeException("number", "Zero is not a valid field number.");
csharptest's avatar
csharptest committed
624
                }
625 626 627
                if (HasField(number))
                {
                    GetFieldBuilder(number).MergeFrom(field);
csharptest's avatar
csharptest committed
628
                }
629 630 631 632 633 634
                else
                {
                    // Optimization:  We could call getFieldBuilder(number).mergeFrom(field)
                    // in this case, but that would create a copy of the Field object.
                    // We'd rather reuse the one passed to us, so call AddField() instead.
                    AddField(number, field);
csharptest's avatar
csharptest committed
635
                }
636 637 638
                return this;
            }

639
            internal void MergeFrom(ICodedInputStream input, ExtensionRegistry extensionRegistry, IBuilder builder)
640
            {
641 642 643
                uint tag;
                string name;
                while (input.ReadTag(out tag, out name))
644
                {
645 646 647 648
                    if (tag == 0 && name != null)
                    {
                        FieldDescriptor fieldByName = builder.DescriptorForType.FindFieldByName(name);
                        if (fieldByName != null)
649
                        {
650
                            tag = WireFormat.MakeTag(fieldByName);
651
                        }
652 653 654 655
                        else
                        {
                            ExtensionInfo extension = extensionRegistry.FindByName(builder.DescriptorForType, name);
                            if (extension != null)
656
                            {
657
                                tag = WireFormat.MakeTag(extension.Descriptor);
658
                            }
659 660
                        }
                    }
661 662
                    if (tag == 0)
                    {
663
                        if (input.SkipField())
664
                        {
665
                            continue; //can't merge unknown without field tag
666
                        }
667 668 669
                        break;
                    }

670
                    if (!MergeFieldFrom(input, extensionRegistry, builder, tag, name))
671 672 673 674
                    {
                        // end group tag
                        break;
                    }
csharptest's avatar
csharptest committed
675
                }
676
            }
csharptest's avatar
csharptest committed
677

678
            /// <summary>
679
            /// Like <see cref="MergeFrom(ICodedInputStream, ExtensionRegistry, IBuilder)" />
680 681 682 683 684 685 686
            /// but parses a single field.
            /// </summary>
            /// <param name="input">The input to read the field from</param>
            /// <param name="extensionRegistry">Registry to use when an extension field is encountered</param>
            /// <param name="builder">Builder to merge field into, if it's a known field</param>
            /// <param name="tag">The tag, which should already have been read from the input</param>
            /// <returns>true unless the tag is an end-group tag</returns>
687
            internal bool MergeFieldFrom(ICodedInputStream input,
688 689
                                         ExtensionRegistry extensionRegistry, IBuilder builder, uint tag,
                                         string fieldName)
690
            {
691 692 693 694
                if (tag == 0 && fieldName != null)
                {
                    FieldDescriptor fieldByName = builder.DescriptorForType.FindFieldByName(fieldName);
                    if (fieldByName != null)
695
                    {
696
                        tag = WireFormat.MakeTag(fieldByName);
697
                    }
698 699 700 701
                    else
                    {
                        ExtensionInfo extension = extensionRegistry.FindByName(builder.DescriptorForType, fieldName);
                        if (extension != null)
702
                        {
703
                            tag = WireFormat.MakeTag(extension.Descriptor);
704
                        }
705 706 707
                    }
                }

708 709 710 711 712 713
                MessageDescriptor type = builder.DescriptorForType;
                if (type.Options.MessageSetWireFormat && tag == WireFormat.MessageSetTag.ItemStart)
                {
                    MergeMessageSetExtensionFromCodedStream(input, extensionRegistry, builder);
                    return true;
                }
csharptest's avatar
csharptest committed
714

715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
                WireFormat.WireType wireType = WireFormat.GetTagWireType(tag);
                int fieldNumber = WireFormat.GetTagFieldNumber(tag);

                FieldDescriptor field;
                IMessageLite defaultFieldInstance = null;

                if (type.IsExtensionNumber(fieldNumber))
                {
                    ExtensionInfo extension = extensionRegistry[type, fieldNumber];
                    if (extension == null)
                    {
                        field = null;
                    }
                    else
                    {
                        field = extension.Descriptor;
                        defaultFieldInstance = extension.DefaultInstance;
                    }
                }
                else
                {
                    field = type.FindFieldByNumber(fieldNumber);
                }
csharptest's avatar
csharptest committed
738

739
                // Unknown field or wrong wire type. Skip.
740
                if (field == null)
741 742 743
                {
                    return MergeFieldFrom(tag, input);
                }
744 745 746 747 748 749 750 751
                if (wireType != WireFormat.GetWireType(field))
                {
                    WireFormat.WireType expectedType = WireFormat.GetWireType(field.FieldType);
                    if (wireType == expectedType)
                    {
                        //Allowed as of 2.3, this is unpacked data for a packed array
                    }
                    else if (field.IsRepeated && wireType == WireFormat.WireType.LengthDelimited &&
752 753
                             (expectedType == WireFormat.WireType.Varint || expectedType == WireFormat.WireType.Fixed32 ||
                              expectedType == WireFormat.WireType.Fixed64))
754 755 756 757
                    {
                        //Allowed as of 2.3, this is packed data for an unpacked array
                    }
                    else
758
                    {
759
                        return MergeFieldFrom(tag, input);
760
                    }
761
                }
csharptest's avatar
csharptest committed
762

763
                switch (field.FieldType)
764
                {
765 766
                    case FieldType.Group:
                    case FieldType.Message:
767
                        {
768 769 770
                            IBuilderLite subBuilder = (defaultFieldInstance != null)
                                                          ? defaultFieldInstance.WeakCreateBuilderForType()
                                                          : builder.CreateBuilderForField(field);
771 772
                            if (!field.IsRepeated)
                            {
773
                                subBuilder.WeakMergeFrom((IMessageLite) builder[field]);
774
                                if (field.FieldType == FieldType.Group)
775
                                {
776
                                    input.ReadGroup(field.FieldNumber, subBuilder, extensionRegistry);
777
                                }
778
                                else
779
                                {
780
                                    input.ReadMessage(subBuilder, extensionRegistry);
781
                                }
782 783 784
                                builder[field] = subBuilder.WeakBuild();
                            }
                            else
785
                            {
786 787
                                List<IMessageLite> list = new List<IMessageLite>();
                                if (field.FieldType == FieldType.Group)
788 789 790 791
                                {
                                    input.ReadGroupArray(tag, fieldName, list, subBuilder.WeakDefaultInstanceForType,
                                                         extensionRegistry);
                                }
792
                                else
793 794 795 796
                                {
                                    input.ReadMessageArray(tag, fieldName, list, subBuilder.WeakDefaultInstanceForType,
                                                           extensionRegistry);
                                }
797 798

                                foreach (IMessageLite m in list)
799
                                {
800
                                    builder.WeakAddRepeatedField(field, m);
801
                                }
802 803
                                return true;
                            }
804
                            break;
805
                        }
806
                    case FieldType.Enum:
807
                        {
808
                            if (!field.IsRepeated)
809
                            {
810 811 812
                                object unknown;
                                IEnumLite value = null;
                                if (input.ReadEnum(ref value, out unknown, field.EnumType))
813
                                {
814
                                    builder[field] = value;
815 816 817 818 819
                                }
                                else if (unknown is int)
                                {
                                    MergeVarintField(fieldNumber, (ulong) (int) unknown);
                                }
820
                            }
821
                            else
822
                            {
823 824 825
                                ICollection<object> unknown;
                                List<IEnumLite> list = new List<IEnumLite>();
                                input.ReadEnumArray(tag, fieldName, list, out unknown, field.EnumType);
826

827
                                foreach (IEnumLite en in list)
828
                                {
829
                                    builder.WeakAddRepeatedField(field, en);
830
                                }
831 832

                                if (unknown != null)
833
                                {
834
                                    foreach (object oval in unknown)
835
                                    {
836
                                        if (oval is int)
837 838 839 840
                                        {
                                            MergeVarintField(fieldNumber, (ulong) (int) oval);
                                        }
                                    }
841 842 843
                                }
                            }
                            break;
844 845 846 847 848 849 850
                        }
                    default:
                        {
                            if (!field.IsRepeated)
                            {
                                object value = null;
                                if (input.ReadPrimitiveField(field.FieldType, ref value))
851
                                {
852
                                    builder[field] = value;
853
                                }
854 855 856 857 858 859
                            }
                            else
                            {
                                List<object> list = new List<object>();
                                input.ReadPrimitiveArray(field.FieldType, tag, fieldName, list);
                                foreach (object oval in list)
860
                                {
861
                                    builder.WeakAddRepeatedField(field, oval);
862
                                }
863 864 865
                            }
                            break;
                        }
866 867 868
                }
                return true;
            }
csharptest's avatar
csharptest committed
869

870 871 872
            /// <summary>
            /// Called by MergeFieldFrom to parse a MessageSet extension.
            /// </summary>
873
            private void MergeMessageSetExtensionFromCodedStream(ICodedInputStream input,
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
                                                                 ExtensionRegistry extensionRegistry, IBuilder builder)
            {
                MessageDescriptor type = builder.DescriptorForType;

                // The wire format for MessageSet is:
                //   message MessageSet {
                //     repeated group Item = 1 {
                //       required int32 typeId = 2;
                //       required bytes message = 3;
                //     }
                //   }
                // "typeId" is the extension's field number.  The extension can only be
                // a message type, where "message" contains the encoded bytes of that
                // message.
                //
                // In practice, we will probably never see a MessageSet item in which
                // the message appears before the type ID, or where either field does not
                // appear exactly once.  However, in theory such cases are valid, so we
                // should be prepared to accept them.

                int typeId = 0;
                ByteString rawBytes = null; // If we encounter "message" before "typeId"
                IBuilderLite subBuilder = null;
                FieldDescriptor field = null;

899
                uint lastTag = WireFormat.MessageSetTag.ItemStart;
900 901 902
                uint tag;
                string name;
                while (input.ReadTag(out tag, out name))
903
                {
904 905
                    if (tag == 0 && name != null)
                    {
906 907 908 909 910 911 912 913
                        if (name == "type_id")
                        {
                            tag = WireFormat.MessageSetTag.TypeID;
                        }
                        else if (name == "message")
                        {
                            tag = WireFormat.MessageSetTag.Message;
                        }
914
                    }
915 916
                    if (tag == 0)
                    {
917
                        if (input.SkipField())
918
                        {
919
                            continue; //can't merge unknown without field tag
920
                        }
921 922 923
                        break;
                    }

924
                    lastTag = tag;
925 926
                    if (tag == WireFormat.MessageSetTag.TypeID)
                    {
927
                        typeId = 0;
928
                        // Zero is not a valid type ID.
929
                        if (input.ReadInt32(ref typeId) && typeId != 0)
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
                        {
                            ExtensionInfo extension = extensionRegistry[type, typeId];
                            if (extension != null)
                            {
                                field = extension.Descriptor;
                                subBuilder = extension.DefaultInstance.WeakCreateBuilderForType();
                                IMessageLite originalMessage = (IMessageLite) builder[field];
                                if (originalMessage != null)
                                {
                                    subBuilder.WeakMergeFrom(originalMessage);
                                }
                                if (rawBytes != null)
                                {
                                    // We already encountered the message.  Parse it now.
                                    // TODO(jonskeet): Check this is okay. It's subtly different from the Java, as it doesn't create an input stream from rawBytes.
                                    // In fact, why don't we just call MergeFrom(rawBytes)? And what about the extension registry?
                                    subBuilder.WeakMergeFrom(rawBytes.CreateCodedInput());
                                    rawBytes = null;
                                }
                            }
                            else
                            {
                                // Unknown extension number.  If we already saw data, put it
                                // in rawBytes.
                                if (rawBytes != null)
                                {
                                    MergeField(typeId, UnknownField.CreateBuilder().AddLengthDelimited(rawBytes).Build());
                                    rawBytes = null;
                                }
                            }
                        }
                    }
                    else if (tag == WireFormat.MessageSetTag.Message)
                    {
964
                        if (subBuilder != null)
965 966 967 968 969
                        {
                            // We already know the type, so we can parse directly from the input
                            // with no copying.  Hooray!
                            input.ReadMessage(subBuilder, extensionRegistry);
                        }
970 971 972 973 974 975 976 977 978
                        else if (input.ReadBytes(ref rawBytes))
                        {
                            if (typeId != 0)
                            {
                                // We don't know how to parse this.  Ignore it.
                                MergeField(typeId,
                                           UnknownField.CreateBuilder().AddLengthDelimited(rawBytes).Build());
                            }
                        }
979 980 981 982
                    }
                    else
                    {
                        // Unknown tag.  Skip it.
983
                        if (!input.SkipField())
984 985 986 987 988
                        {
                            break; // end of group
                        }
                    }
                }
csharptest's avatar
csharptest committed
989

990
                if (lastTag != WireFormat.MessageSetTag.ItemEnd)
991
                {
992
                    throw InvalidProtocolBufferException.InvalidEndTag();
993
                }
csharptest's avatar
csharptest committed
994

995 996 997 998 999
                if (subBuilder != null)
                {
                    builder[field] = subBuilder.WeakBuild();
                }
            }
csharptest's avatar
csharptest committed
1000

1001
            #region IBuilderLite Members
csharptest's avatar
csharptest committed
1002

1003 1004 1005 1006
            bool IBuilderLite.IsInitialized
            {
                get { return fields != null; }
            }
csharptest's avatar
csharptest committed
1007

1008 1009 1010 1011
            IBuilderLite IBuilderLite.WeakClear()
            {
                return Clear();
            }
csharptest's avatar
csharptest committed
1012

1013 1014 1015 1016
            IBuilderLite IBuilderLite.WeakMergeFrom(IMessageLite message)
            {
                return MergeFrom((UnknownFieldSet) message);
            }
csharptest's avatar
csharptest committed
1017

1018 1019 1020 1021
            IBuilderLite IBuilderLite.WeakMergeFrom(ByteString data)
            {
                return MergeFrom(data);
            }
csharptest's avatar
csharptest committed
1022

1023 1024 1025 1026 1027
            IBuilderLite IBuilderLite.WeakMergeFrom(ByteString data, ExtensionRegistry registry)
            {
                return MergeFrom(data);
            }

1028
            IBuilderLite IBuilderLite.WeakMergeFrom(ICodedInputStream input)
1029 1030 1031
            {
                return MergeFrom(input);
            }
csharptest's avatar
csharptest committed
1032

1033
            IBuilderLite IBuilderLite.WeakMergeFrom(ICodedInputStream input, ExtensionRegistry registry)
1034 1035 1036
            {
                return MergeFrom(input);
            }
csharptest's avatar
csharptest committed
1037

1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
            IMessageLite IBuilderLite.WeakBuild()
            {
                return Build();
            }

            IMessageLite IBuilderLite.WeakBuildPartial()
            {
                return Build();
            }

            IBuilderLite IBuilderLite.WeakClone()
            {
                return Build().WeakToBuilder();
            }

            IMessageLite IBuilderLite.WeakDefaultInstanceForType
            {
                get { return DefaultInstance; }
            }

            #endregion
        }
csharptest's avatar
csharptest committed
1060
    }
1061
}