First pass at the mutable API. Quite a bit more to do - in particular, it's pretty slow right now.

pull/515/head
Jon Skeet 10 years ago
parent f52426827e
commit e38294a62d
  1. 86
      csharp/protos/extest/unittest_issues.proto
  2. 548
      csharp/src/ProtocolBuffers.Test/AbstractMessageTest.cs
  3. 2
      csharp/src/ProtocolBuffers.Test/ByteStringTest.cs
  4. 64
      csharp/src/ProtocolBuffers.Test/CodedInputStreamTest.cs
  5. 23
      csharp/src/ProtocolBuffers.Test/CodedOutputStreamTest.cs
  6. 125
      csharp/src/ProtocolBuffers.Test/Collections/PopsicleListTest.cs
  7. 18
      csharp/src/ProtocolBuffers.Test/Compatibility/BinaryCompatibilityTests.cs
  8. 227
      csharp/src/ProtocolBuffers.Test/Compatibility/CompatibilityTests.cs
  9. 35
      csharp/src/ProtocolBuffers.Test/Compatibility/DictionaryCompatibilityTests.cs
  10. 43
      csharp/src/ProtocolBuffers.Test/Compatibility/JsonCompatibilityTests.cs
  11. 38
      csharp/src/ProtocolBuffers.Test/Compatibility/TestResources.cs
  12. 35
      csharp/src/ProtocolBuffers.Test/Compatibility/TextCompatibilityTests.cs
  13. 45
      csharp/src/ProtocolBuffers.Test/Compatibility/XmlCompatibilityTests.cs
  14. BIN
      csharp/src/ProtocolBuffers.Test/Compatibility/google_message1.dat
  15. BIN
      csharp/src/ProtocolBuffers.Test/Compatibility/google_message2.dat
  16. 82
      csharp/src/ProtocolBuffers.Test/DeprecatedMemberTest.cs
  17. 152
      csharp/src/ProtocolBuffers.Test/DescriptorsTest.cs
  18. 276
      csharp/src/ProtocolBuffers.Test/DynamicMessageTest.cs
  19. 200
      csharp/src/ProtocolBuffers.Test/ExtendableMessageTest.cs
  20. 198
      csharp/src/ProtocolBuffers.Test/FieldPresenceTest.cs
  21. 102
      csharp/src/ProtocolBuffers.Test/GeneratedBuilderTest.cs
  22. 911
      csharp/src/ProtocolBuffers.Test/GeneratedMessageTest.cs
  23. 10
      csharp/src/ProtocolBuffers.Test/IssuesTest.cs
  24. 90
      csharp/src/ProtocolBuffers.Test/MessageStreamIteratorTest.cs
  25. 78
      csharp/src/ProtocolBuffers.Test/MessageStreamWriterTest.cs
  26. 344
      csharp/src/ProtocolBuffers.Test/MessageTest.cs
  27. 82
      csharp/src/ProtocolBuffers.Test/MessageUtilTest.cs
  28. 81
      csharp/src/ProtocolBuffers.Test/NameHelpersTest.cs
  29. 62
      csharp/src/ProtocolBuffers.Test/ProtocolBuffers.Test.csproj
  30. 1033
      csharp/src/ProtocolBuffers.Test/ReflectionTester.cs
  31. 50
      csharp/src/ProtocolBuffers.Test/RepeatedFieldTest.cs
  32. 166
      csharp/src/ProtocolBuffers.Test/ReusableBuilderTest.cs
  33. 22
      csharp/src/ProtocolBuffers.Test/TestCornerCases.cs
  34. 277
      csharp/src/ProtocolBuffers.Test/TestMimeMessageFormats.cs
  35. 4547
      csharp/src/ProtocolBuffers.Test/TestProtos/GoogleSize.cs
  36. 6612
      csharp/src/ProtocolBuffers.Test/TestProtos/GoogleSpeed.cs
  37. 33878
      csharp/src/ProtocolBuffers.Test/TestProtos/Unittest.cs
  38. 7543
      csharp/src/ProtocolBuffers.Test/TestProtos/UnittestCustomOptions.cs
  39. 732
      csharp/src/ProtocolBuffers.Test/TestProtos/UnittestDropUnknownFields.cs
  40. 36189
      csharp/src/ProtocolBuffers.Test/TestProtos/UnittestEnormousDescriptor.cs
  41. 2277
      csharp/src/ProtocolBuffers.Test/TestProtos/UnittestExtrasXmltest.cs
  42. 347
      csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImport.cs
  43. 165
      csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImportProto3.cs
  44. 333
      csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImportPublic.cs
  45. 150
      csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImportPublicProto3.cs
  46. 2571
      csharp/src/ProtocolBuffers.Test/TestProtos/UnittestIssues.cs
  47. 1824
      csharp/src/ProtocolBuffers.Test/TestProtos/UnittestMset.cs
  48. 3876
      csharp/src/ProtocolBuffers.Test/TestProtos/UnittestNoFieldPresence.cs
  49. 738
      csharp/src/ProtocolBuffers.Test/TestProtos/UnittestOptimizeFor.cs
  50. 6060
      csharp/src/ProtocolBuffers.Test/TestProtos/UnittestProto3.cs
  51. 809
      csharp/src/ProtocolBuffers.Test/TestProtos/UnknownEnumTest.cs
  52. 83
      csharp/src/ProtocolBuffers.Test/TestReaderForUrlEncoded.cs
  53. 301
      csharp/src/ProtocolBuffers.Test/TestResources.cs
  54. 1862
      csharp/src/ProtocolBuffers.Test/TestUtil.cs
  55. 498
      csharp/src/ProtocolBuffers.Test/TestWriterFormatJson.cs
  56. 468
      csharp/src/ProtocolBuffers.Test/TestWriterFormatXml.cs
  57. 560
      csharp/src/ProtocolBuffers.Test/TextFormatTest.cs
  58. 431
      csharp/src/ProtocolBuffers.Test/UnknownFieldSetTest.cs
  59. 255
      csharp/src/ProtocolBuffers.Test/WireFormatTest.cs
  60. 274
      csharp/src/ProtocolBuffers/AbstractBuilder.cs
  61. 264
      csharp/src/ProtocolBuffers/AbstractBuilderLite.cs
  62. 293
      csharp/src/ProtocolBuffers/AbstractMessage.cs
  63. 140
      csharp/src/ProtocolBuffers/AbstractMessageLite.cs
  64. 2
      csharp/src/ProtocolBuffers/ByteArray.cs
  65. 20
      csharp/src/ProtocolBuffers/ByteString.cs
  66. 163
      csharp/src/ProtocolBuffers/CodedInputStream.cs
  67. 71
      csharp/src/ProtocolBuffers/CodedOutputStream.ComputeSize.cs
  68. 338
      csharp/src/ProtocolBuffers/CodedOutputStream.cs
  69. 2
      csharp/src/ProtocolBuffers/Collections/Dictionaries.cs
  70. 2
      csharp/src/ProtocolBuffers/Collections/Enumerables.cs
  71. 58
      csharp/src/ProtocolBuffers/Collections/IPopsicleList.cs
  72. 2
      csharp/src/ProtocolBuffers/Collections/Lists.cs
  73. 208
      csharp/src/ProtocolBuffers/Collections/PopsicleList.cs
  74. 2
      csharp/src/ProtocolBuffers/Collections/ReadOnlyDictionary.cs
  75. 168
      csharp/src/ProtocolBuffers/Collections/RepeatedField.cs
  76. 47
      csharp/src/ProtocolBuffers/Collections/RepeatedFieldExtensions.cs
  77. 12724
      csharp/src/ProtocolBuffers/DescriptorProtos/DescriptorProtoFile.cs
  78. 2
      csharp/src/ProtocolBuffers/DescriptorProtos/IDescriptorProto.cs
  79. 2
      csharp/src/ProtocolBuffers/DescriptorProtos/PartialClasses.cs
  80. 5
      csharp/src/ProtocolBuffers/Descriptors/DescriptorBase.cs
  81. 4
      csharp/src/ProtocolBuffers/Descriptors/DescriptorPool.cs
  82. 4
      csharp/src/ProtocolBuffers/Descriptors/DescriptorUtil.cs
  83. 13
      csharp/src/ProtocolBuffers/Descriptors/DescriptorValidationException.cs
  84. 31
      csharp/src/ProtocolBuffers/Descriptors/EnumDescriptor.cs
  85. 7
      csharp/src/ProtocolBuffers/Descriptors/EnumValueDescriptor.cs
  86. 223
      csharp/src/ProtocolBuffers/Descriptors/FieldDescriptor.cs
  87. 4
      csharp/src/ProtocolBuffers/Descriptors/FieldMappingAttribute.cs
  88. 2
      csharp/src/ProtocolBuffers/Descriptors/FieldType.cs
  89. 55
      csharp/src/ProtocolBuffers/Descriptors/FileDescriptor.cs
  90. 4
      csharp/src/ProtocolBuffers/Descriptors/IDescriptor.cs
  91. 4
      csharp/src/ProtocolBuffers/Descriptors/IndexedDescriptorBase.cs
  92. 2
      csharp/src/ProtocolBuffers/Descriptors/MappedType.cs
  93. 30
      csharp/src/ProtocolBuffers/Descriptors/MessageDescriptor.cs
  94. 4
      csharp/src/ProtocolBuffers/Descriptors/MethodDescriptor.cs
  95. 4
      csharp/src/ProtocolBuffers/Descriptors/OneofDescriptor.cs
  96. 2
      csharp/src/ProtocolBuffers/Descriptors/PackageDescriptor.cs
  97. 8
      csharp/src/ProtocolBuffers/Descriptors/ServiceDescriptor.cs
  98. 624
      csharp/src/ProtocolBuffers/DynamicMessage.cs
  99. 85
      csharp/src/ProtocolBuffers/EnumHelper.cs
  100. 234
      csharp/src/ProtocolBuffers/EnumLite.cs
  101. Some files were not shown because too many files have changed in this diff Show More

@ -1,4 +1,4 @@
syntax = "proto2";
syntax = "proto3";
// These proto descriptors have at one time been reported as an issue or defect.
// They are kept here to replicate the issue, and continue to verify the fix.
@ -9,65 +9,6 @@ option csharp_namespace = "UnitTest.Issues.TestProtos";
package unittest_issues;
option optimize_for = SPEED;
// The following is a representative set of features
/*
enum EnumOptions {
ONE = 0;
TWO = 1;
THREE = 2;
}
message TestBasicChild
{
repeated EnumOptions options = 3;
optional bytes binary = 4;
}
message TestBasicNoFields {
}
message TestBasicRescursive {
optional TestBasicRescursive child = 1;
}
message TestBasicMessage {
optional int64 number = 6;
repeated int32 numbers = 2;
optional string text = 3;
repeated string textlines = 700;
optional bool valid = 5;
optional TestBasicChild child = 1;
repeated group Children = 401
{
repeated EnumOptions options = 3;
optional bytes binary = 4;
}
extensions 100 to 199;
}
message TestBasicExtension {
required int32 number = 1;
}
extend TestBasicMessage {
optional EnumOptions extension_enum = 101;
optional string extension_text = 102;
repeated int32 extension_number = 103 [packed = true];
optional TestBasicExtension extension_message = 199;
}
// Issue for non-qualified type reference in new services generation
option (google.protobuf.csharp_file_options).service_generator_type = IRPCDISPATCH;
service TestGenericService {
rpc Foo(TestBasicNoFields) returns (TestBasicMessage);
rpc Bar(TestBasicNoFields) returns (TestBasicMessage);
}
*/
// Old issue 13: http://code.google.com/p/protobuf-csharp-port/issues/detail?id=13
// New issue 309: https://github.com/google/protobuf/issues/309
@ -90,27 +31,17 @@ service TestGenericService {
// optional int32 _01 = 1;
// }
// Issue 28: Circular message dependencies result in null defaults for DefaultInstance
message MyMessageAReferenceB {
required MyMessageBReferenceA value = 1;
}
message MyMessageBReferenceA {
required MyMessageAReferenceB value = 1;
}
// issue 19 - negative enum values
enum NegativeEnum {
NEGATIVE_ENUM_ZERO = 0;
FiveBelow = -5;
MinusOne = -1;
Zero = 0;
}
message NegativeEnumMessage {
optional NegativeEnum value = 1;
repeated NegativeEnum values = 2;
NegativeEnum value = 1;
repeated NegativeEnum values = 2 [packed = false];
repeated NegativeEnum packed_values = 3 [packed=true];
}
@ -121,21 +52,22 @@ message DeprecatedChild {
}
enum DeprecatedEnum {
DEPRECATED_ZERO = 0;
one = 1;
}
message DeprecatedFieldsMessage {
optional int32 PrimitiveValue = 1 [deprecated = true];
int32 PrimitiveValue = 1 [deprecated = true];
repeated int32 PrimitiveArray = 2 [deprecated = true];
optional DeprecatedChild MessageValue = 3 [deprecated = true];
DeprecatedChild MessageValue = 3 [deprecated = true];
repeated DeprecatedChild MessageArray = 4 [deprecated = true];
optional DeprecatedEnum EnumValue = 5 [deprecated = true];
DeprecatedEnum EnumValue = 5 [deprecated = true];
repeated DeprecatedEnum EnumArray = 6 [deprecated = true];
}
// Issue 45: http://code.google.com/p/protobuf-csharp-port/issues/detail?id=45
message ItemField {
optional int32 item = 1;
int32 item = 1;
}

@ -1,548 +0,0 @@
#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.Collections.Generic;
using System.IO;
using Google.ProtocolBuffers.Descriptors;
using Google.ProtocolBuffers.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers
{
public class AbstractMessageTest
{
[Test]
public void Clear()
{
AbstractMessageWrapper message =
new AbstractMessageWrapper.Builder(TestAllTypes.CreateBuilder(TestUtil.GetAllSet())).Clear().Build();
TestUtil.AssertClear((TestAllTypes) message.WrappedMessage);
}
[Test]
public void Copy()
{
AbstractMessageWrapper message =
new AbstractMessageWrapper.Builder(TestAllTypes.CreateBuilder()).MergeFrom(TestUtil.GetAllSet()).Build();
TestUtil.AssertAllFieldsSet((TestAllTypes) message.WrappedMessage);
}
[Test]
public void CreateAndBuild()
{
TestAllTypes.CreateBuilder()
.Build();
}
[Test]
public void SerializedSize()
{
TestAllTypes message = TestUtil.GetAllSet();
IMessage abstractMessage = new AbstractMessageWrapper(TestUtil.GetAllSet());
Assert.AreEqual(message.SerializedSize, abstractMessage.SerializedSize);
}
[Test]
public void Serialization()
{
IMessage abstractMessage = new AbstractMessageWrapper(TestUtil.GetAllSet());
TestUtil.AssertAllFieldsSet(TestAllTypes.ParseFrom(abstractMessage.ToByteString()));
Assert.AreEqual(TestUtil.GetAllSet().ToByteString(), abstractMessage.ToByteString());
}
[Test]
public void Parsing()
{
IBuilder builder = new AbstractMessageWrapper.Builder(TestAllTypes.CreateBuilder());
AbstractMessageWrapper message =
(AbstractMessageWrapper) builder.WeakMergeFrom(TestUtil.GetAllSet().ToByteString()).WeakBuild();
TestUtil.AssertAllFieldsSet((TestAllTypes) message.WrappedMessage);
}
[Test]
public void PackedSerialization()
{
IMessage abstractMessage = new AbstractMessageWrapper(TestUtil.GetPackedSet());
TestUtil.AssertPackedFieldsSet(TestPackedTypes.ParseFrom(abstractMessage.ToByteString()));
Assert.AreEqual(TestUtil.GetPackedSet().ToByteString(), abstractMessage.ToByteString());
}
[Test]
public void PackedParsing()
{
AbstractMessageWrapper.Builder builder = new AbstractMessageWrapper.Builder(TestPackedTypes.CreateBuilder());
AbstractMessageWrapper message = builder.MergeFrom(TestUtil.GetPackedSet().ToByteString()).Build();
TestUtil.AssertPackedFieldsSet((TestPackedTypes)message.WrappedMessage);
}
[Test]
public void UnpackedParsingOfPackedInput()
{
byte[] bytes = TestUtil.GetPackedSet().ToByteArray();
TestUnpackedTypes message = TestUnpackedTypes.ParseFrom(bytes);
TestUtil.AssertUnpackedFieldsSet(message);
}
[Test]
public void PackedParsingOfUnpackedInput()
{
byte[] bytes = TestUnpackedTypes.ParseFrom(TestUtil.GetPackedSet().ToByteArray()).ToByteArray();
TestPackedTypes message = TestPackedTypes.ParseFrom(bytes);
TestUtil.AssertPackedFieldsSet(message);
}
[Test]
public void UnpackedParsingOfPackedInputExtensions()
{
byte[] bytes = TestUtil.GetPackedSet().ToByteArray();
ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
Unittest.RegisterAllExtensions(registry);
UnittestImport.RegisterAllExtensions(registry);
TestUnpackedExtensions message = TestUnpackedExtensions.ParseFrom(bytes, registry);
TestUtil.AssertUnpackedExtensionsSet(message);
}
[Test]
public void PackedParsingOfUnpackedInputExtensions()
{
byte[] bytes = TestUnpackedTypes.ParseFrom(TestUtil.GetPackedSet().ToByteArray()).ToByteArray();
ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
Unittest.RegisterAllExtensions(registry);
TestPackedExtensions message = TestPackedExtensions.ParseFrom(bytes, registry);
TestUtil.AssertPackedExtensionsSet(message);
}
[Test]
public void OptimizedForSize()
{
// We're mostly only Checking that this class was compiled successfully.
TestOptimizedForSize message = TestOptimizedForSize.CreateBuilder().SetI(1).Build();
message = TestOptimizedForSize.ParseFrom(message.ToByteString());
Assert.AreEqual(2, message.SerializedSize);
}
// -----------------------------------------------------------------
// Tests for isInitialized().
private static readonly TestRequired TestRequiredUninitialized = TestRequired.DefaultInstance;
private static readonly TestRequired TestRequiredInitialized =
TestRequired.CreateBuilder().SetA(1).SetB(2).SetC(3).Build();
[Test]
public void IsInitialized()
{
TestRequired.Builder builder = TestRequired.CreateBuilder();
AbstractMessageWrapper.Builder abstractBuilder = new AbstractMessageWrapper.Builder(builder);
Assert.IsFalse(abstractBuilder.IsInitialized);
builder.A = 1;
Assert.IsFalse(abstractBuilder.IsInitialized);
builder.B = 1;
Assert.IsFalse(abstractBuilder.IsInitialized);
builder.C = 1;
Assert.IsTrue(abstractBuilder.IsInitialized);
}
[Test]
public void ForeignIsInitialized()
{
TestRequiredForeign.Builder builder = TestRequiredForeign.CreateBuilder();
AbstractMessageWrapper.Builder abstractBuilder = new AbstractMessageWrapper.Builder(builder);
Assert.IsTrue(abstractBuilder.IsInitialized);
builder.SetOptionalMessage(TestRequiredUninitialized);
Assert.IsFalse(abstractBuilder.IsInitialized);
builder.SetOptionalMessage(TestRequiredInitialized);
Assert.IsTrue(abstractBuilder.IsInitialized);
builder.AddRepeatedMessage(TestRequiredUninitialized);
Assert.IsFalse(abstractBuilder.IsInitialized);
builder.SetRepeatedMessage(0, TestRequiredInitialized);
Assert.IsTrue(abstractBuilder.IsInitialized);
}
// -----------------------------------------------------------------
// Tests for mergeFrom
private static readonly TestAllTypes MergeSource = TestAllTypes.CreateBuilder()
.SetOptionalInt32(1)
.SetOptionalString("foo")
.SetOptionalForeignMessage(ForeignMessage.DefaultInstance)
.AddRepeatedString("bar")
.Build();
private static readonly TestAllTypes MergeDest = TestAllTypes.CreateBuilder()
.SetOptionalInt64(2)
.SetOptionalString("baz")
.SetOptionalForeignMessage(ForeignMessage.CreateBuilder().SetC(3).Build())
.AddRepeatedString("qux")
.Build();
private const string MergeResultText = "optional_int32: 1\n" +
"optional_int64: 2\n" +
"optional_string: \"foo\"\n" +
"optional_foreign_message {\n" +
" c: 3\n" +
"}\n" +
"repeated_string: \"qux\"\n" +
"repeated_string: \"bar\"\n";
[Test]
public void MergeFrom()
{
AbstractMessageWrapper result = (AbstractMessageWrapper)
new AbstractMessageWrapper.Builder(TestAllTypes.CreateBuilder(MergeDest))
.MergeFrom(MergeSource)
.Build();
Assert.AreEqual(MergeResultText, result.ToString());
}
// -----------------------------------------------------------------
// Tests for equals and hashCode
[Test]
public void EqualsAndHashCode()
{
TestAllTypes a = TestUtil.GetAllSet();
TestAllTypes b = TestAllTypes.CreateBuilder().Build();
TestAllTypes c = TestAllTypes.CreateBuilder(b).AddRepeatedString("x").Build();
TestAllTypes d = TestAllTypes.CreateBuilder(c).AddRepeatedString("y").Build();
TestAllExtensions e = TestUtil.GetAllExtensionsSet();
TestAllExtensions f = TestAllExtensions.CreateBuilder(e)
.AddExtension(Unittest.RepeatedInt32Extension, 999).Build();
CheckEqualsIsConsistent(a);
CheckEqualsIsConsistent(b);
CheckEqualsIsConsistent(c);
CheckEqualsIsConsistent(d);
CheckEqualsIsConsistent(e);
CheckEqualsIsConsistent(f);
CheckNotEqual(a, b);
CheckNotEqual(a, c);
CheckNotEqual(a, d);
CheckNotEqual(a, e);
CheckNotEqual(a, f);
CheckNotEqual(b, c);
CheckNotEqual(b, d);
CheckNotEqual(b, e);
CheckNotEqual(b, f);
CheckNotEqual(c, d);
CheckNotEqual(c, e);
CheckNotEqual(c, f);
CheckNotEqual(d, e);
CheckNotEqual(d, f);
CheckNotEqual(e, f);
// Deserializing into the TestEmptyMessage such that every field is an UnknownFieldSet.Field
TestEmptyMessage eUnknownFields = TestEmptyMessage.ParseFrom(e.ToByteArray());
TestEmptyMessage fUnknownFields = TestEmptyMessage.ParseFrom(f.ToByteArray());
CheckNotEqual(eUnknownFields, fUnknownFields);
CheckEqualsIsConsistent(eUnknownFields);
CheckEqualsIsConsistent(fUnknownFields);
// Subseqent reconstitutions should be identical
TestEmptyMessage eUnknownFields2 = TestEmptyMessage.ParseFrom(e.ToByteArray());
CheckEqualsIsConsistent(eUnknownFields, eUnknownFields2);
}
/// <summary>
/// Asserts that the given protos are equal and have the same hash code.
/// </summary>
private static void CheckEqualsIsConsistent(IMessage message)
{
// Object should be equal to itself.
Assert.AreEqual(message, message);
// Object should be equal to a dynamic copy of itself.
DynamicMessage dynamic = DynamicMessage.CreateBuilder(message).Build();
CheckEqualsIsConsistent(message, dynamic);
}
/// <summary>
/// Asserts that the given protos are equal and have the same hash code.
/// </summary>
private static void CheckEqualsIsConsistent(IMessage message1, IMessage message2)
{
// Not using Assert.AreEqual as that checks for type equality, which isn't
// what we want bearing in mind the dynamic message checks.
Assert.IsTrue(message1.Equals(message2));
Assert.IsTrue(message2.Equals(message1));
Assert.AreEqual(message2.GetHashCode(), message1.GetHashCode());
}
/// <summary>
/// Asserts that the given protos are not equal and have different hash codes.
/// </summary>
/// <remarks>
/// It's valid for non-equal objects to have the same hash code, so
/// this test is stricter than it needs to be. However, this should happen
/// relatively rarely. (If this test fails, it's probably still due to a bug.)
/// </remarks>
private static void CheckNotEqual(IMessage m1, IMessage m2)
{
String equalsError = string.Format("{0} should not be equal to {1}", m1, m2);
Assert.IsFalse(m1.Equals(m2), equalsError);
Assert.IsFalse(m2.Equals(m1), equalsError);
Assert.IsFalse(m1.GetHashCode() == m2.GetHashCode(),
string.Format("{0} should have a different hash code from {1}", m1, m2));
}
/// <summary>
/// Extends AbstractMessage and wraps some other message object. The methods
/// of the Message interface which aren't explicitly implemented by
/// AbstractMessage are forwarded to the wrapped object. This allows us to
/// test that AbstractMessage's implementations work even if the wrapped
/// object does not use them.
/// </summary>
private class AbstractMessageWrapper : AbstractMessage<AbstractMessageWrapper, AbstractMessageWrapper.Builder>
{
private readonly IMessage wrappedMessage;
public IMessage WrappedMessage
{
get { return wrappedMessage; }
}
public AbstractMessageWrapper(IMessage wrappedMessage)
{
this.wrappedMessage = wrappedMessage;
}
public override MessageDescriptor DescriptorForType
{
get { return wrappedMessage.DescriptorForType; }
}
public override AbstractMessageWrapper DefaultInstanceForType
{
get { return new AbstractMessageWrapper(wrappedMessage.WeakDefaultInstanceForType); }
}
public override IDictionary<FieldDescriptor, object> AllFields
{
get { return wrappedMessage.AllFields; }
}
public override bool HasField(FieldDescriptor field)
{
return wrappedMessage.HasField(field);
}
public override bool HasOneof(OneofDescriptor oneof)
{
return wrappedMessage.HasOneof(oneof);
}
public override FieldDescriptor OneofFieldDescriptor(OneofDescriptor oneof)
{
return wrappedMessage.OneofFieldDescriptor(oneof);
}
public override object this[FieldDescriptor field]
{
get { return wrappedMessage[field]; }
}
public override object this[FieldDescriptor field, int index]
{
get { return wrappedMessage[field, index]; }
}
public override int GetRepeatedFieldCount(FieldDescriptor field)
{
return wrappedMessage.GetRepeatedFieldCount(field);
}
public override UnknownFieldSet UnknownFields
{
get { return wrappedMessage.UnknownFields; }
}
public override Builder CreateBuilderForType()
{
return new Builder(wrappedMessage.WeakCreateBuilderForType());
}
public override Builder ToBuilder()
{
return new Builder(wrappedMessage.WeakToBuilder());
}
internal class Builder : AbstractBuilder<AbstractMessageWrapper, Builder>
{
private readonly IBuilder wrappedBuilder;
protected override Builder ThisBuilder
{
get { return this; }
}
internal Builder(IBuilder wrappedBuilder)
{
this.wrappedBuilder = wrappedBuilder;
}
public override Builder MergeFrom(AbstractMessageWrapper other)
{
wrappedBuilder.WeakMergeFrom(other.wrappedMessage);
return this;
}
public override bool IsInitialized
{
get { return wrappedBuilder.IsInitialized; }
}
public override IDictionary<FieldDescriptor, object> AllFields
{
get { return wrappedBuilder.AllFields; }
}
public override object this[FieldDescriptor field]
{
get { return wrappedBuilder[field]; }
set { wrappedBuilder[field] = value; }
}
public override MessageDescriptor DescriptorForType
{
get { return wrappedBuilder.DescriptorForType; }
}
public override int GetRepeatedFieldCount(FieldDescriptor field)
{
return wrappedBuilder.GetRepeatedFieldCount(field);
}
public override object this[FieldDescriptor field, int index]
{
get { return wrappedBuilder[field, index]; }
set { wrappedBuilder[field, index] = value; }
}
public override bool HasField(FieldDescriptor field)
{
return wrappedBuilder.HasField(field);
}
public override bool HasOneof(OneofDescriptor oneof)
{
return wrappedBuilder.HasOneof(oneof);
}
public override FieldDescriptor OneofFieldDescriptor(OneofDescriptor oneof)
{
return wrappedBuilder.OneofFieldDescriptor(oneof);
}
public override UnknownFieldSet UnknownFields
{
get { return wrappedBuilder.UnknownFields; }
set { wrappedBuilder.UnknownFields = value; }
}
public override AbstractMessageWrapper Build()
{
return new AbstractMessageWrapper(wrappedBuilder.WeakBuild());
}
public override AbstractMessageWrapper BuildPartial()
{
return new AbstractMessageWrapper(wrappedBuilder.WeakBuildPartial());
}
public override Builder Clone()
{
return new Builder(wrappedBuilder.WeakClone());
}
public override AbstractMessageWrapper DefaultInstanceForType
{
get { return new AbstractMessageWrapper(wrappedBuilder.WeakDefaultInstanceForType); }
}
public override Builder ClearField(FieldDescriptor field)
{
wrappedBuilder.WeakClearField(field);
return this;
}
public override Builder ClearOneof(OneofDescriptor oneof)
{
wrappedBuilder.WeakClearOneof(oneof);
return this;
}
public override Builder AddRepeatedField(FieldDescriptor field, object value)
{
wrappedBuilder.WeakAddRepeatedField(field, value);
return this;
}
public override IBuilder CreateBuilderForField(FieldDescriptor field)
{
wrappedBuilder.CreateBuilderForField(field);
return this;
}
public override Builder MergeFrom(IMessage other)
{
wrappedBuilder.WeakMergeFrom(other);
return this;
}
public override Builder MergeFrom(ICodedInputStream input, ExtensionRegistry extensionRegistry)
{
wrappedBuilder.WeakMergeFrom(input, extensionRegistry);
return this;
}
}
}
}
}

@ -38,7 +38,7 @@ using System;
using System.Text;
using NUnit.Framework;
namespace Google.ProtocolBuffers
namespace Google.Protobuf
{
public class ByteStringTest
{

@ -37,11 +37,12 @@
using System;
using System.Collections.Generic;
using System.IO;
using Google.ProtocolBuffers.Descriptors;
using Google.ProtocolBuffers.TestProtos;
using Google.Protobuf.Collections;
using Google.Protobuf.Descriptors;
using Google.Protobuf.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers
namespace Google.Protobuf
{
public class CodedInputStreamTest
{
@ -231,7 +232,7 @@ namespace Google.ProtocolBuffers
Assert.AreEqual(0x7FFFFFFFFFFFFFFFL, CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFEL));
Assert.AreEqual(unchecked((long) 0x8000000000000000L), CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFFL));
}
/*
[Test]
public void ReadWholeMessage()
{
@ -273,7 +274,7 @@ namespace Google.ProtocolBuffers
unknownFields.MergeFieldFrom(tag, input1);
input2.SkipField();
}
}
}*/
/// <summary>
/// Test that a bug in SkipRawBytes has been fixed: if the skip
@ -290,7 +291,7 @@ namespace Google.ProtocolBuffers
input.PopLimit(limit);
Assert.AreEqual(2, input.ReadRawByte());
}
/*
public void ReadHugeBlob()
{
// Allocate and initialize a 1MB blob.
@ -318,7 +319,7 @@ namespace Google.ProtocolBuffers
.SetOptionalBytes(TestUtil.GetAllSet().OptionalBytes)
.Build();
TestUtil.AssertAllFieldsSet(message3);
}
}*/
[Test]
public void ReadMaliciouslyLargeBlob()
@ -348,12 +349,11 @@ namespace Google.ProtocolBuffers
{
if (depth == 0)
{
return TestRecursiveMessage.CreateBuilder().SetI(5).Build();
return new TestRecursiveMessage { I = 5 };
}
else
{
return TestRecursiveMessage.CreateBuilder()
.SetA(MakeRecursiveMessage(depth - 1)).Build();
return new TestRecursiveMessage { A = MakeRecursiveMessage(depth - 1) };
}
}
@ -361,12 +361,12 @@ namespace Google.ProtocolBuffers
{
if (depth == 0)
{
Assert.IsFalse(message.HasA);
Assert.IsNull(message.A);
Assert.AreEqual(5, message.I);
}
else
{
Assert.IsTrue(message.HasA);
Assert.IsNotNull(message.A);
AssertMessageDepth(message.A, depth - 1);
}
}
@ -377,15 +377,16 @@ namespace Google.ProtocolBuffers
ByteString data64 = MakeRecursiveMessage(64).ToByteString();
ByteString data65 = MakeRecursiveMessage(65).ToByteString();
AssertMessageDepth(TestRecursiveMessage.ParseFrom(data64), 64);
AssertMessageDepth(TestRecursiveMessage.Parser.ParseFrom(data64), 64);
Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.ParseFrom(data65));
Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(data65));
CodedInputStream input = data64.CreateCodedInput();
input.SetRecursionLimit(8);
Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.ParseFrom(input));
Assert.Throws<InvalidProtocolBufferException>(() => TestRecursiveMessage.Parser.ParseFrom(input));
}
/*
[Test]
public void SizeLimit()
{
@ -396,7 +397,7 @@ namespace Google.ProtocolBuffers
input.SetSizeLimit(16);
Assert.Throws<InvalidProtocolBufferException>(() => TestAllTypes.ParseFrom(input));
}
}*/
[Test]
public void ResetSizeCounter()
@ -465,17 +466,16 @@ namespace Google.ProtocolBuffers
}
}
enum TestNegEnum { None = 0, Value = -2 }
enum TestNegEnum : long { None = 0, Value = -2 }
[Test]
public void TestNegativeEnum()
{
byte[] bytes = new byte[10] { 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01 };
CodedInputStream input = CodedInputStream.CreateInstance(bytes);
object unk;
TestNegEnum val = TestNegEnum.None;
Assert.IsTrue(input.ReadEnum(ref val, out unk));
Assert.IsTrue(input.ReadEnum(ref val));
Assert.IsTrue(input.IsAtEnd);
Assert.AreEqual(TestNegEnum.Value, val);
}
@ -487,7 +487,7 @@ namespace Google.ProtocolBuffers
int msgSize = 1 + 1 + arraySize;
byte[] bytes = new byte[msgSize];
CodedOutputStream output = CodedOutputStream.CreateInstance(bytes);
output.WritePackedInt32Array(8, "", arraySize, new int[] { 0, -1, -2, -3, -4, -5 });
output.WritePackedInt32Array(8, "", new RepeatedField<int> { 0, -1, -2, -3, -4, -5 });
Assert.AreEqual(0, output.SpaceLeft);
@ -497,15 +497,12 @@ namespace Google.ProtocolBuffers
Assert.IsTrue(input.ReadTag(out tag, out name));
List<TestNegEnum> values = new List<TestNegEnum>();
ICollection<object> unk;
input.ReadEnumArray(tag, name, values, out unk);
input.ReadEnumArray(tag, name, values);
Assert.AreEqual(2, values.Count);
Assert.AreEqual(6, values.Count);
Assert.AreEqual(TestNegEnum.None, values[0]);
Assert.AreEqual(TestNegEnum.Value, values[1]);
Assert.NotNull(unk);
Assert.AreEqual(4, unk.Count);
Assert.AreEqual(TestNegEnum.Value, values[2]);
// TODO(jonskeet): Test unknown value preservation
}
[Test]
@ -515,7 +512,7 @@ namespace Google.ProtocolBuffers
int msgSize = arraySize;
byte[] bytes = new byte[msgSize];
CodedOutputStream output = CodedOutputStream.CreateInstance(bytes);
output.WriteInt32Array(8, "", new int[] { 0, -1, -2, -3, -4, -5 });
output.WriteInt32Array(8, "", new RepeatedField<int> { 0, -1, -2, -3, -4, -5 });
Assert.AreEqual(0, output.SpaceLeft);
@ -525,15 +522,12 @@ namespace Google.ProtocolBuffers
Assert.IsTrue(input.ReadTag(out tag, out name));
List<TestNegEnum> values = new List<TestNegEnum>();
ICollection<object> unk;
input.ReadEnumArray(tag, name, values, out unk);
input.ReadEnumArray(tag, name, values);
Assert.AreEqual(2, values.Count);
Assert.AreEqual(6, values.Count);
Assert.AreEqual(TestNegEnum.None, values[0]);
Assert.AreEqual(TestNegEnum.Value, values[1]);
Assert.NotNull(unk);
Assert.AreEqual(4, unk.Count);
Assert.AreEqual(TestNegEnum.Value, values[2]);
// TODO(jonskeet): Test unknown value preservation
}
//Issue 71: CodedInputStream.ReadBytes go to slow path unnecessarily

@ -37,10 +37,10 @@
using System;
using System.Collections.Generic;
using System.IO;
using Google.ProtocolBuffers.TestProtos;
using Google.Protobuf.Collections;
using NUnit.Framework;
namespace Google.ProtocolBuffers
namespace Google.Protobuf
{
public class CodedOutputStreamTest
{
@ -195,6 +195,7 @@ namespace Google.ProtocolBuffers
0x9abcdef012345678UL);
}
/*
[Test]
public void WriteWholeMessage()
{
@ -228,6 +229,7 @@ namespace Google.ProtocolBuffers
TestUtil.AssertEqualBytes(TestUtil.GetGoldenPackedFieldsMessage().ToByteArray(),
rawBytes);
}
*/
[Test]
public void EncodeZigZag32()
@ -294,25 +296,27 @@ namespace Google.ProtocolBuffers
public void TestNegativeEnumNoTag()
{
Assert.AreEqual(10, CodedOutputStream.ComputeInt32SizeNoTag(-2));
Assert.AreEqual(10, CodedOutputStream.ComputeEnumSizeNoTag(-2));
Assert.AreEqual(10, CodedOutputStream.ComputeEnumSizeNoTag(TestNegEnum.Value));
byte[] bytes = new byte[10];
CodedOutputStream output = CodedOutputStream.CreateInstance(bytes);
output.WriteEnumNoTag(-2);
output.WriteEnumNoTag(TestNegEnum.Value);
Assert.AreEqual(0, output.SpaceLeft);
Assert.AreEqual("FE-FF-FF-FF-FF-FF-FF-FF-FF-01", BitConverter.ToString(bytes));
}
enum TestNegEnum : long { None = 0, Value = -2 }
[Test]
public void TestNegativeEnumWithTag()
{
Assert.AreEqual(11, CodedOutputStream.ComputeInt32Size(8, -2));
Assert.AreEqual(11, CodedOutputStream.ComputeEnumSize(8, -2));
Assert.AreEqual(11, CodedOutputStream.ComputeEnumSize(8, TestNegEnum.Value));
byte[] bytes = new byte[11];
CodedOutputStream output = CodedOutputStream.CreateInstance(bytes);
output.WriteEnum(8, "", -2, -2);
output.WriteEnum(8, "", TestNegEnum.Value);
Assert.AreEqual(0, output.SpaceLeft);
//fyi, 0x40 == 0x08 << 3 + 0, field num + wire format shift
@ -326,7 +330,8 @@ namespace Google.ProtocolBuffers
int msgSize = 1 + 1 + arraySize;
byte[] bytes = new byte[msgSize];
CodedOutputStream output = CodedOutputStream.CreateInstance(bytes);
output.WritePackedEnumArray(8, "", arraySize, new int[] { 0, -1, -2, -3, -4, -5 });
output.WritePackedEnumArray(8, "", new RepeatedField<TestNegEnum> {
0, (TestNegEnum) (-1), TestNegEnum.Value, (TestNegEnum) (-3), (TestNegEnum) (-4), (TestNegEnum) (-5) });
Assert.AreEqual(0, output.SpaceLeft);
@ -350,8 +355,8 @@ namespace Google.ProtocolBuffers
int msgSize = arraySize;
byte[] bytes = new byte[msgSize];
CodedOutputStream output = CodedOutputStream.CreateInstance(bytes);
output.WriteEnumArray(8, "", new int[] { 0, -1, -2, -3, -4, -5 });
output.WriteEnumArray(8, "", new RepeatedField<TestNegEnum> {
0, (TestNegEnum) (-1), TestNegEnum.Value, (TestNegEnum) (-3), (TestNegEnum) (-4), (TestNegEnum) (-5) });
Assert.AreEqual(0, output.SpaceLeft);
CodedInputStream input = CodedInputStream.CreateInstance(bytes);

@ -1,125 +0,0 @@
#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.Collections.Generic;
using NUnit.Framework;
namespace Google.ProtocolBuffers.Collections
{
public class PopsicleListTest
{
[Test]
public void MutatingOperationsOnFrozenList()
{
PopsicleList<string> list = new PopsicleList<string>();
list.MakeReadOnly();
Assert.Throws<NotSupportedException>(() => list.Add(""));
Assert.Throws<NotSupportedException>(() => list.Clear());
Assert.Throws<NotSupportedException>(() => list.Insert(0, ""));
Assert.Throws<NotSupportedException>(() => list.Remove(""));
Assert.Throws<NotSupportedException>(() => list.RemoveAt(0));
Assert.Throws<NotSupportedException>(() => list.Add(new[] { "", "" }));
}
[Test]
public void NonMutatingOperationsOnFrozenList()
{
PopsicleList<string> list = new PopsicleList<string>();
list.MakeReadOnly();
Assert.IsFalse(list.Contains(""));
Assert.AreEqual(0, list.Count);
list.CopyTo(new string[5], 0);
list.GetEnumerator();
Assert.AreEqual(-1, list.IndexOf(""));
Assert.IsTrue(list.IsReadOnly);
}
[Test]
public void MutatingOperationsOnFluidList()
{
PopsicleList<string> list = new PopsicleList<string>();
list.Add("");
list.Clear();
list.Insert(0, "");
list.Remove("");
list.Add("x"); // Just to make the next call valid
list.RemoveAt(0);
}
[Test]
public void NonMutatingOperationsOnFluidList()
{
PopsicleList<string> list = new PopsicleList<string>();
Assert.IsFalse(list.Contains(""));
Assert.AreEqual(0, list.Count);
list.CopyTo(new string[5], 0);
list.GetEnumerator();
Assert.AreEqual(-1, list.IndexOf(""));
Assert.IsFalse(list.IsReadOnly);
}
[Test]
public void DoesNotAddNullEnumerable()
{
PopsicleList<string> list = new PopsicleList<string>();
Assert.Throws<ArgumentNullException>(() => list.Add((IEnumerable<string>) null));
}
[Test]
public void DoesNotAddRangeWithNull()
{
PopsicleList<string> list = new PopsicleList<string>();
// TODO(jonskeet): Change to ArgumentException? The argument isn't null...
Assert.Throws<ArgumentNullException>(() => list.Add(new[] {"a", "b", null}));
}
[Test]
public void DoesNotAddNull()
{
PopsicleList<string> list = new PopsicleList<string>();
Assert.Throws<ArgumentNullException>(() => list.Add((string) null));
}
[Test]
public void DoesNotSetNull()
{
PopsicleList<string> list = new PopsicleList<string>();
list.Add("a");
Assert.Throws<ArgumentNullException>(() => list[0] = null);
}
}
}

@ -1,18 +0,0 @@
using System;
namespace Google.ProtocolBuffers.Compatibility
{
public class BinaryCompatibilityTests : CompatibilityTests
{
protected override object SerializeMessage<TMessage, TBuilder>(TMessage message)
{
byte[] bresult = message.ToByteArray();
return Convert.ToBase64String(bresult);
}
protected override TBuilder DeserializeMessage<TMessage, TBuilder>(object message, TBuilder builder, ExtensionRegistry registry)
{
return builder.MergeFrom((byte[])Convert.FromBase64String((string)message), registry);
}
}
}

@ -1,227 +0,0 @@
using System;
using Google.ProtocolBuffers.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers.Compatibility
{
/// <summary>
/// This abstract base implements several tests to ensure that well-known messages can be written
/// and read to/from various formats without losing data. Implementations override the two serialization
/// methods to provide the tests with the means to read and write for a given format.
/// </summary>
public abstract class CompatibilityTests
{
protected abstract object SerializeMessage<TMessage, TBuilder>(TMessage message)
where TMessage : IMessageLite<TMessage, TBuilder>
where TBuilder : IBuilderLite<TMessage, TBuilder>;
protected abstract TBuilder DeserializeMessage<TMessage, TBuilder>(object message, TBuilder builder, ExtensionRegistry registry)
where TMessage : IMessageLite<TMessage, TBuilder>
where TBuilder : IBuilderLite<TMessage, TBuilder>;
protected virtual void AssertOutputEquals(object lhs, object rhs)
{
Assert.AreEqual(lhs, rhs);
}
[Test]
public virtual void RoundTripWithEmptyChildMessageSize()
{
SizeMessage1 msg = SizeMessage1.CreateBuilder()
.SetField100(100)
.SetField15(SizeMessage1SubMessage.DefaultInstance)
.BuildPartial();
byte[] contents = msg.ToByteArray();
object content = SerializeMessage<SizeMessage1, SizeMessage1.Builder>(msg);
SizeMessage1 copy = DeserializeMessage<SizeMessage1, SizeMessage1.Builder>(content, SizeMessage1.CreateBuilder(), ExtensionRegistry.Empty).BuildPartial();
Assert.AreEqual(msg, copy);
AssertOutputEquals(content, SerializeMessage<SizeMessage1, SizeMessage1.Builder>(copy));
Assert.AreEqual(Convert.ToBase64String(contents), Convert.ToBase64String(copy.ToByteArray()));
}
[Test]
public virtual void RoundTripWithEmptyChildMessageSpeed()
{
SpeedMessage1 msg = SpeedMessage1.CreateBuilder()
.SetField100(100)
.SetField15(SpeedMessage1SubMessage.DefaultInstance)
.BuildPartial();
byte[] contents = msg.ToByteArray();
object content = SerializeMessage<SpeedMessage1, SpeedMessage1.Builder>(msg);
SpeedMessage1 copy = DeserializeMessage<SpeedMessage1, SpeedMessage1.Builder>(content, SpeedMessage1.CreateBuilder(), ExtensionRegistry.Empty).BuildPartial();
Assert.AreEqual(msg, copy);
AssertOutputEquals(content, SerializeMessage<SpeedMessage1, SpeedMessage1.Builder>(copy));
Assert.AreEqual(Convert.ToBase64String(contents), Convert.ToBase64String(copy.ToByteArray()));
}
[Test]
public virtual void RoundTripMessage1OptimizeSize()
{
SizeMessage1 msg = SizeMessage1.CreateBuilder().MergeFrom(TestResources.google_message1).Build();
object content = SerializeMessage<SizeMessage1, SizeMessage1.Builder>(msg);
SizeMessage1 copy = DeserializeMessage<SizeMessage1, SizeMessage1.Builder>(content, SizeMessage1.CreateBuilder(), ExtensionRegistry.Empty).Build();
Assert.AreEqual(msg, copy);
AssertOutputEquals(content, SerializeMessage<SizeMessage1, SizeMessage1.Builder>(copy));
Assert.AreEqual(Convert.ToBase64String(TestResources.google_message1), Convert.ToBase64String(copy.ToByteArray()));
}
[Test]
public virtual void RoundTripMessage2OptimizeSize()
{
SizeMessage2 msg = SizeMessage2.CreateBuilder().MergeFrom(TestResources.google_message2).Build();
object content = SerializeMessage<SizeMessage2, SizeMessage2.Builder>(msg);
SizeMessage2 copy = DeserializeMessage<SizeMessage2, SizeMessage2.Builder>(content, SizeMessage2.CreateBuilder(), ExtensionRegistry.Empty).Build();
Assert.AreEqual(msg, copy);
AssertOutputEquals(content, SerializeMessage<SizeMessage2, SizeMessage2.Builder>(copy));
Assert.AreEqual(Convert.ToBase64String(TestResources.google_message2), Convert.ToBase64String(copy.ToByteArray()));
}
[Test]
public virtual void RoundTripMessage1OptimizeSpeed()
{
SpeedMessage1 msg = SpeedMessage1.CreateBuilder().MergeFrom(TestResources.google_message1).Build();
object content = SerializeMessage<SpeedMessage1, SpeedMessage1.Builder>(msg);
SpeedMessage1 copy = DeserializeMessage<SpeedMessage1, SpeedMessage1.Builder>(content, SpeedMessage1.CreateBuilder(), ExtensionRegistry.Empty).Build();
Assert.AreEqual(msg, copy);
AssertOutputEquals(content, SerializeMessage<SpeedMessage1, SpeedMessage1.Builder>(copy));
Assert.AreEqual(Convert.ToBase64String(TestResources.google_message1), Convert.ToBase64String(copy.ToByteArray()));
}
[Test]
public virtual void RoundTripMessage2OptimizeSpeed()
{
SpeedMessage2 msg = SpeedMessage2.CreateBuilder().MergeFrom(TestResources.google_message2).Build();
object content = SerializeMessage<SpeedMessage2, SpeedMessage2.Builder>(msg);
SpeedMessage2 copy = DeserializeMessage<SpeedMessage2, SpeedMessage2.Builder>(content, SpeedMessage2.CreateBuilder(), ExtensionRegistry.Empty).Build();
Assert.AreEqual(msg, copy);
AssertOutputEquals(content, SerializeMessage<SpeedMessage2, SpeedMessage2.Builder>(copy));
Assert.AreEqual(Convert.ToBase64String(TestResources.google_message2), Convert.ToBase64String(copy.ToByteArray()));
}
#region Test message builders
protected static TestAllTypes.Builder AddAllTypes(TestAllTypes.Builder builder)
{
return builder.SetOptionalInt32(1001)
.SetOptionalInt64(1001)
.SetOptionalUint32(1001)
.SetOptionalUint64(1001)
.SetOptionalSint32(-1001)
.SetOptionalSint64(-1001)
.SetOptionalFixed32(1001)
.SetOptionalFixed64(1001)
.SetOptionalSfixed32(-1001)
.SetOptionalSfixed64(-1001)
.SetOptionalFloat(1001.1001f)
.SetOptionalDouble(1001.1001)
.SetOptionalBool(true)
.SetOptionalString("this is a string value")
.SetOptionalBytes(ByteString.CopyFromUtf8("this is an array of bytes"))
.SetOptionalGroup(new TestAllTypes.Types.OptionalGroup.Builder().SetA(1001))
.SetOptionalNestedMessage(new TestAllTypes.Types.NestedMessage.Builder().SetBb(1001))
.SetOptionalNestedEnum(TestAllTypes.Types.NestedEnum.FOO)
;
}
protected static TestAllTypes.Builder AddRepeatedTypes(TestAllTypes.Builder builder, int size)
{
//repeated values
for (int i = 0; i < size; i++)
builder.AddRepeatedInt32(1001 + i)
.AddRepeatedInt64(1001)
.AddRepeatedUint32(1001)
.AddRepeatedUint64(1001)
.AddRepeatedSint32(-1001)
.AddRepeatedSint64(-1001)
.AddRepeatedFixed32(1001)
.AddRepeatedFixed64(1001)
.AddRepeatedSfixed32(-1001)
.AddRepeatedSfixed64(-1001)
.AddRepeatedFloat(1001.1001f)
.AddRepeatedDouble(1001.1001)
.AddRepeatedBool(true)
.AddRepeatedString("this is a string value")
.AddRepeatedBytes(ByteString.CopyFromUtf8("this is an array of bytes"))
.AddRepeatedGroup(new TestAllTypes.Types.RepeatedGroup.Builder().SetA(1001))
.AddRepeatedNestedMessage(new TestAllTypes.Types.NestedMessage.Builder().SetBb(1001))
.AddRepeatedNestedEnum(TestAllTypes.Types.NestedEnum.FOO)
;
return builder;
}
protected static TestPackedTypes.Builder AddPackedTypes(TestPackedTypes.Builder builder, int size)
{
for(int i=0; i < size; i++ )
builder.AddPackedInt32(1001)
.AddPackedInt64(1001)
.AddPackedUint32(1001)
.AddPackedUint64(1001)
.AddPackedSint32(-1001)
.AddPackedSint64(-1001)
.AddPackedFixed32(1001)
.AddPackedFixed64(1001)
.AddPackedSfixed32(-1001)
.AddPackedSfixed64(-1001)
.AddPackedFloat(1001.1001f)
.AddPackedDouble(1001.1001)
.AddPackedBool(true)
.AddPackedEnum(ForeignEnum.FOREIGN_FOO)
;
return builder;
}
#endregion
[Test]
public void TestRoundTripAllTypes()
{
TestAllTypes msg = AddAllTypes(new TestAllTypes.Builder()).Build();
object content = SerializeMessage<TestAllTypes, TestAllTypes.Builder>(msg);
TestAllTypes copy = DeserializeMessage<TestAllTypes, TestAllTypes.Builder>(content, TestAllTypes.CreateBuilder(), ExtensionRegistry.Empty).Build();
Assert.AreEqual(msg, copy);
AssertOutputEquals(content, SerializeMessage<TestAllTypes, TestAllTypes.Builder>(copy));
Assert.AreEqual(Convert.ToBase64String(msg.ToByteArray()), Convert.ToBase64String(copy.ToByteArray()));
}
[Test]
public void TestRoundTripRepeatedTypes()
{
TestAllTypes msg = AddRepeatedTypes(new TestAllTypes.Builder(), 5).Build();
object content = SerializeMessage<TestAllTypes, TestAllTypes.Builder>(msg);
TestAllTypes copy = DeserializeMessage<TestAllTypes, TestAllTypes.Builder>(content, TestAllTypes.CreateBuilder(), ExtensionRegistry.Empty).Build();
Assert.AreEqual(msg, copy);
AssertOutputEquals(content, SerializeMessage<TestAllTypes, TestAllTypes.Builder>(copy));
Assert.AreEqual(Convert.ToBase64String(msg.ToByteArray()), Convert.ToBase64String(copy.ToByteArray()));
}
[Test]
public void TestRoundTripPackedTypes()
{
TestPackedTypes msg = AddPackedTypes(new TestPackedTypes.Builder(), 5).Build();
object content = SerializeMessage<TestPackedTypes, TestPackedTypes.Builder>(msg);
TestPackedTypes copy = DeserializeMessage<TestPackedTypes, TestPackedTypes.Builder>(content, TestPackedTypes.CreateBuilder(), ExtensionRegistry.Empty).Build();
Assert.AreEqual(msg, copy);
AssertOutputEquals(content, SerializeMessage<TestPackedTypes, TestPackedTypes.Builder>(copy));
Assert.AreEqual(Convert.ToBase64String(msg.ToByteArray()), Convert.ToBase64String(copy.ToByteArray()));
}
}
}

@ -1,35 +0,0 @@
using System;
using System.Collections.Generic;
using Google.ProtocolBuffers.Serialization;
using NUnit.Framework;
namespace Google.ProtocolBuffers.Compatibility
{
[TestFixture]
public class DictionaryCompatibilityTests : CompatibilityTests
{
protected override object SerializeMessage<TMessage, TBuilder>(TMessage message)
{
DictionaryWriter writer = new DictionaryWriter();
writer.WriteMessage(message);
return writer.ToDictionary();
}
protected override TBuilder DeserializeMessage<TMessage, TBuilder>(object message, TBuilder builder, ExtensionRegistry registry)
{
new DictionaryReader((IDictionary<string, object>)message).Merge(builder);
return builder;
}
protected override void AssertOutputEquals(object lhs, object rhs)
{
IDictionary<string, object> left = (IDictionary<string, object>)lhs;
IDictionary<string, object> right = (IDictionary<string, object>)rhs;
Assert.AreEqual(
String.Join(",", new List<string>(left.Keys).ToArray()),
String.Join(",", new List<string>(right.Keys).ToArray())
);
}
}
}

@ -1,43 +0,0 @@
using System.IO;
using Google.ProtocolBuffers.Serialization;
using NUnit.Framework;
namespace Google.ProtocolBuffers.Compatibility
{
[TestFixture]
public class JsonCompatibilityTests : CompatibilityTests
{
protected override object SerializeMessage<TMessage, TBuilder>(TMessage message)
{
StringWriter sw = new StringWriter();
JsonFormatWriter.CreateInstance(sw)
.WriteMessage(message);
return sw.ToString();
}
protected override TBuilder DeserializeMessage<TMessage, TBuilder>(object message, TBuilder builder, ExtensionRegistry registry)
{
JsonFormatReader.CreateInstance((string)message).Merge(builder);
return builder;
}
}
[TestFixture]
public class JsonCompatibilityFormattedTests : CompatibilityTests
{
protected override object SerializeMessage<TMessage, TBuilder>(TMessage message)
{
StringWriter sw = new StringWriter();
JsonFormatWriter.CreateInstance(sw)
.Formatted()
.WriteMessage(message);
return sw.ToString();
}
protected override TBuilder DeserializeMessage<TMessage, TBuilder>(object message, TBuilder builder, ExtensionRegistry registry)
{
JsonFormatReader.CreateInstance((string)message).Merge(builder);
return builder;
}
}
}

@ -1,38 +0,0 @@
using System.IO;
using NUnit.Framework;
namespace Google.ProtocolBuffers.Compatibility
{
static class TestResources
{
public static byte[] google_message1
{
get
{
Stream resource = typeof(TestResources).Assembly.GetManifestResourceStream(
typeof(TestResources).Namespace + ".google_message1.dat");
Assert.NotNull(resource);
byte[] bytes = new byte[resource.Length];
int amtRead = resource.Read(bytes, 0, bytes.Length);
Assert.AreEqual(bytes.Length, amtRead);
return bytes;
}
}
public static byte[] google_message2
{
get
{
Stream resource = typeof(TestResources).Assembly.GetManifestResourceStream(
typeof(TestResources).Namespace + ".google_message2.dat");
Assert.NotNull(resource);
byte[] bytes = new byte[resource.Length];
int amtRead = resource.Read(bytes, 0, bytes.Length);
Assert.AreEqual(bytes.Length, amtRead);
return bytes;
}
}
}
}

@ -1,35 +0,0 @@
using System.IO;
using NUnit.Framework;
namespace Google.ProtocolBuffers.Compatibility
{
[TestFixture]
public class TextCompatibilityTests : CompatibilityTests
{
protected override object SerializeMessage<TMessage, TBuilder>(TMessage message)
{
StringWriter text = new StringWriter();
message.PrintTo(text);
return text.ToString();
}
protected override TBuilder DeserializeMessage<TMessage, TBuilder>(object message, TBuilder builder, ExtensionRegistry registry)
{
TextFormat.Merge(new StringReader((string)message), registry, (IBuilder)builder);
return builder;
}
//This test can take a very long time to run.
[Test]
public override void RoundTripMessage2OptimizeSize()
{
//base.RoundTripMessage2OptimizeSize();
}
//This test can take a very long time to run.
[Test]
public override void RoundTripMessage2OptimizeSpeed()
{
//base.RoundTripMessage2OptimizeSpeed();
}
}
}

@ -1,45 +0,0 @@
using System.IO;
using System.Xml;
using Google.ProtocolBuffers.Serialization;
using NUnit.Framework;
namespace Google.ProtocolBuffers.Compatibility
{
[TestFixture]
public class XmlCompatibilityTests : CompatibilityTests
{
protected override object SerializeMessage<TMessage, TBuilder>(TMessage message)
{
StringWriter text = new StringWriter();
XmlFormatWriter writer = XmlFormatWriter.CreateInstance(text);
writer.WriteMessage("root", message);
return text.ToString();
}
protected override TBuilder DeserializeMessage<TMessage, TBuilder>(object message, TBuilder builder, ExtensionRegistry registry)
{
XmlFormatReader reader = XmlFormatReader.CreateInstance((string)message);
return reader.Merge("root", builder, registry);
}
}
[TestFixture]
public class XmlCompatibilityFormattedTests : CompatibilityTests
{
protected override object SerializeMessage<TMessage, TBuilder>(TMessage message)
{
StringWriter text = new StringWriter();
XmlWriter xwtr = XmlWriter.Create(text, new XmlWriterSettings { Indent = true, IndentChars = " " });
XmlFormatWriter writer = XmlFormatWriter.CreateInstance(xwtr).SetOptions(XmlWriterOptions.OutputNestedArrays);
writer.WriteMessage("root", message);
return text.ToString();
}
protected override TBuilder DeserializeMessage<TMessage, TBuilder>(object message, TBuilder builder, ExtensionRegistry registry)
{
XmlFormatReader reader = XmlFormatReader.CreateInstance((string)message).SetOptions(XmlReaderOptions.ReadNestedArrays);
return reader.Merge("root", builder, registry);
}
}
}

@ -1,9 +1,9 @@
using System;
using System.Reflection;
using UnitTest.Issues.TestProtos;
using Google.Protobuf.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers
namespace Google.Protobuf
{
public class DeprecatedMemberTest
{
@ -16,84 +16,8 @@ namespace Google.ProtocolBuffers
[Test]
public void TestDepreatedPrimitiveValue()
{
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("HasPrimitiveValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("PrimitiveValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("HasPrimitiveValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("PrimitiveValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("ClearPrimitiveValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetPrimitiveValue"));
}
[Test]
public void TestDepreatedPrimitiveArray()
{
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("PrimitiveArrayList"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("PrimitiveArrayCount"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetMethod("GetPrimitiveArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("PrimitiveArrayList"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("PrimitiveArrayCount"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("GetPrimitiveArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetPrimitiveArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddPrimitiveArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddRangePrimitiveArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("ClearPrimitiveArray"));
}
[Test]
public void TestDepreatedMessageValue()
{
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("HasMessageValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("MessageValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("HasMessageValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("MessageValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("MergeMessageValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("ClearMessageValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetMessageValue", new[] { typeof(DeprecatedChild) }));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetMessageValue", new[] { typeof(DeprecatedChild.Builder) }));
}
[Test]
public void TestDepreatedMessageArray()
{
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("MessageArrayList"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("MessageArrayCount"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetMethod("GetMessageArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("MessageArrayList"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("MessageArrayCount"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("GetMessageArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetMessageArray", new[] { typeof(int), typeof(DeprecatedChild) }));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetMessageArray", new[] { typeof(int), typeof(DeprecatedChild.Builder) }));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddMessageArray", new[] { typeof(DeprecatedChild) }));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddMessageArray", new[] { typeof(DeprecatedChild.Builder) }));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddRangeMessageArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("ClearMessageArray"));
}
[Test]
public void TestDepreatedEnumValue()
{
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("HasEnumValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("EnumValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("HasEnumValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("EnumValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("ClearEnumValue"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetEnumValue"));
AssertIsDeprecated(typeof(TestDeprecatedFields).GetProperty("DeprecatedInt32"));
}
[Test]
public void TestDepreatedEnumArray()
{
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("EnumArrayList"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("EnumArrayCount"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetMethod("GetEnumArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("EnumArrayList"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("EnumArrayCount"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("GetEnumArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetEnumArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddEnumArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddRangeEnumArray"));
AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("ClearEnumArray"));
}
}
}

@ -34,11 +34,11 @@
#endregion
using Google.ProtocolBuffers.Descriptors;
using Google.ProtocolBuffers.TestProtos;
using Google.Protobuf.Descriptors;
using Google.Protobuf.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers
namespace Google.Protobuf
{
/// <summary>
/// Tests for descriptors. (Not in its own namespace or broken up into individual classes as the
@ -49,21 +49,21 @@ namespace Google.ProtocolBuffers
[Test]
public void FileDescriptor()
{
FileDescriptor file = Unittest.Descriptor;
FileDescriptor file = UnittestProto3.Descriptor;
Assert.AreEqual("google/protobuf/unittest.proto", file.Name);
Assert.AreEqual("google/protobuf/unittest_proto3.proto", file.Name);
Assert.AreEqual("protobuf_unittest", file.Package);
Assert.AreEqual("UnittestProto", file.Options.JavaOuterClassname);
Assert.AreEqual("google/protobuf/unittest.proto", file.Proto.Name);
Assert.AreEqual("google/protobuf/unittest_proto3.proto", file.Proto.Name);
// unittest.proto doesn't have any public imports, but unittest_import.proto does.
Assert.AreEqual(0, file.PublicDependencies.Count);
Assert.AreEqual(1, UnittestImport.Descriptor.PublicDependencies.Count);
Assert.AreEqual(UnittestImportPublic.Descriptor, UnittestImport.Descriptor.PublicDependencies[0]);
Assert.AreEqual(1, UnittestImportProto3.Descriptor.PublicDependencies.Count);
Assert.AreEqual(UnittestImportPublicProto3.Descriptor, UnittestImportProto3.Descriptor.PublicDependencies[0]);
Assert.AreEqual(1, file.Dependencies.Count);
Assert.AreEqual(UnittestImport.Descriptor, file.Dependencies[0]);
Assert.AreEqual(UnittestImportProto3.Descriptor, file.Dependencies[0]);
MessageDescriptor messageType = TestAllTypes.Descriptor;
Assert.AreEqual(messageType, file.MessageTypes[0]);
@ -78,23 +78,12 @@ namespace Google.ProtocolBuffers
Assert.AreEqual(file.EnumTypes[0], file.FindTypeByName<EnumDescriptor>("ForeignEnum"));
Assert.Null(file.FindTypeByName<EnumDescriptor>("NoSuchType"));
Assert.Null(file.FindTypeByName<EnumDescriptor>("protobuf_unittest.ForeignEnum"));
Assert.AreEqual(1, UnittestImport.Descriptor.EnumTypes.Count);
Assert.AreEqual("ImportEnum", UnittestImport.Descriptor.EnumTypes[0].Name);
Assert.AreEqual(1, UnittestImportProto3.Descriptor.EnumTypes.Count);
Assert.AreEqual("ImportEnum", UnittestImportProto3.Descriptor.EnumTypes[0].Name);
for (int i = 0; i < file.EnumTypes.Count; i++)
{
Assert.AreEqual(i, file.EnumTypes[i].Index);
}
FieldDescriptor extension = Unittest.OptionalInt32Extension.Descriptor;
Assert.AreEqual(extension, file.Extensions[0]);
Assert.AreEqual(extension, file.FindTypeByName<FieldDescriptor>("optional_int32_extension"));
Assert.Null(file.FindTypeByName<FieldDescriptor>("no_such_ext"));
Assert.Null(file.FindTypeByName<FieldDescriptor>("protobuf_unittest.optional_int32_extension"));
Assert.AreEqual(0, UnittestImport.Descriptor.Extensions.Count);
for (int i = 0; i < file.Extensions.Count; i++)
{
Assert.AreEqual(i, file.Extensions[i].Index);
}
}
[Test]
@ -105,19 +94,20 @@ namespace Google.ProtocolBuffers
Assert.AreEqual("TestAllTypes", messageType.Name);
Assert.AreEqual("protobuf_unittest.TestAllTypes", messageType.FullName);
Assert.AreEqual(Unittest.Descriptor, messageType.File);
Assert.Null(messageType.ContainingType);
Assert.AreEqual(DescriptorProtos.MessageOptions.DefaultInstance, messageType.Options);
Assert.AreEqual("TestAllTypes", messageType.Proto.Name);
Assert.AreEqual(UnittestProto3.Descriptor, messageType.File);
Assert.IsNull(messageType.ContainingType);
Assert.IsNull(messageType.Options);
Assert.AreEqual("TestAllTypes", messageType.Name);
Assert.AreEqual("NestedMessage", nestedType.Name);
Assert.AreEqual("protobuf_unittest.TestAllTypes.NestedMessage", nestedType.FullName);
Assert.AreEqual(Unittest.Descriptor, nestedType.File);
Assert.AreEqual(UnittestProto3.Descriptor, nestedType.File);
Assert.AreEqual(messageType, nestedType.ContainingType);
FieldDescriptor field = messageType.Fields[0];
Assert.AreEqual("optional_int32", field.Name);
Assert.AreEqual(field, messageType.FindDescriptor<FieldDescriptor>("optional_int32"));
Assert.AreEqual("single_int32", field.Name);
Assert.AreEqual(field, messageType.FindDescriptor<FieldDescriptor>("single_int32"));
Assert.Null(messageType.FindDescriptor<FieldDescriptor>("no_such_field"));
Assert.AreEqual(field, messageType.FindFieldByNumber(1));
Assert.Null(messageType.FindFieldByNumber(571283));
@ -146,115 +136,66 @@ namespace Google.ProtocolBuffers
public void FieldDescriptor()
{
MessageDescriptor messageType = TestAllTypes.Descriptor;
FieldDescriptor primitiveField = messageType.FindDescriptor<FieldDescriptor>("optional_int32");
FieldDescriptor enumField = messageType.FindDescriptor<FieldDescriptor>("optional_nested_enum");
FieldDescriptor messageField = messageType.FindDescriptor<FieldDescriptor>("optional_foreign_message");
FieldDescriptor cordField = messageType.FindDescriptor<FieldDescriptor>("optional_cord");
FieldDescriptor extension = Unittest.OptionalInt32Extension.Descriptor;
FieldDescriptor nestedExtension = TestRequired.Single.Descriptor;
FieldDescriptor primitiveField = messageType.FindDescriptor<FieldDescriptor>("single_int32");
FieldDescriptor enumField = messageType.FindDescriptor<FieldDescriptor>("single_nested_enum");
FieldDescriptor messageField = messageType.FindDescriptor<FieldDescriptor>("single_foreign_message");
Assert.AreEqual("optional_int32", primitiveField.Name);
Assert.AreEqual("protobuf_unittest.TestAllTypes.optional_int32",
Assert.AreEqual("single_int32", primitiveField.Name);
Assert.AreEqual("protobuf_unittest.TestAllTypes.single_int32",
primitiveField.FullName);
Assert.AreEqual(1, primitiveField.FieldNumber);
Assert.AreEqual(messageType, primitiveField.ContainingType);
Assert.AreEqual(Unittest.Descriptor, primitiveField.File);
Assert.AreEqual(UnittestProto3.Descriptor, primitiveField.File);
Assert.AreEqual(FieldType.Int32, primitiveField.FieldType);
Assert.AreEqual(MappedType.Int32, primitiveField.MappedType);
Assert.AreEqual(DescriptorProtos.FieldOptions.DefaultInstance, primitiveField.Options);
Assert.IsFalse(primitiveField.IsExtension);
Assert.AreEqual("optional_int32", primitiveField.Proto.Name);
Assert.AreEqual("optional_nested_enum", enumField.Name);
Assert.IsNull(primitiveField.Options);
Assert.AreEqual("single_nested_enum", enumField.Name);
Assert.AreEqual(FieldType.Enum, enumField.FieldType);
Assert.AreEqual(MappedType.Enum, enumField.MappedType);
// Assert.AreEqual(TestAllTypes.Types.NestedEnum.DescriptorProtoFile, enumField.EnumType);
Assert.AreEqual("optional_foreign_message", messageField.Name);
Assert.AreEqual("single_foreign_message", messageField.Name);
Assert.AreEqual(FieldType.Message, messageField.FieldType);
Assert.AreEqual(MappedType.Message, messageField.MappedType);
Assert.AreEqual(ForeignMessage.Descriptor, messageField.MessageType);
Assert.AreEqual("optional_cord", cordField.Name);
Assert.AreEqual(FieldType.String, cordField.FieldType);
Assert.AreEqual(MappedType.String, cordField.MappedType);
Assert.AreEqual(DescriptorProtos.FieldOptions.Types.CType.CORD, cordField.Options.Ctype);
Assert.AreEqual("optional_int32_extension", extension.Name);
Assert.AreEqual("protobuf_unittest.optional_int32_extension", extension.FullName);
Assert.AreEqual(1, extension.FieldNumber);
Assert.AreEqual(TestAllExtensions.Descriptor, extension.ContainingType);
Assert.AreEqual(Unittest.Descriptor, extension.File);
Assert.AreEqual(FieldType.Int32, extension.FieldType);
Assert.AreEqual(MappedType.Int32, extension.MappedType);
Assert.AreEqual(DescriptorProtos.FieldOptions.DefaultInstance,
extension.Options);
Assert.IsTrue(extension.IsExtension);
Assert.AreEqual(null, extension.ExtensionScope);
Assert.AreEqual("optional_int32_extension", extension.Proto.Name);
Assert.AreEqual("single", nestedExtension.Name);
Assert.AreEqual("protobuf_unittest.TestRequired.single",
nestedExtension.FullName);
Assert.AreEqual(TestRequired.Descriptor,
nestedExtension.ExtensionScope);
}
[Test]
public void FieldDescriptorLabel()
{
FieldDescriptor requiredField =
TestRequired.Descriptor.FindDescriptor<FieldDescriptor>("a");
FieldDescriptor optionalField =
TestAllTypes.Descriptor.FindDescriptor<FieldDescriptor>("optional_int32");
FieldDescriptor singleField =
TestAllTypes.Descriptor.FindDescriptor<FieldDescriptor>("single_int32");
FieldDescriptor repeatedField =
TestAllTypes.Descriptor.FindDescriptor<FieldDescriptor>("repeated_int32");
Assert.IsTrue(requiredField.IsRequired);
Assert.IsFalse(requiredField.IsRepeated);
Assert.IsFalse(optionalField.IsRequired);
Assert.IsFalse(optionalField.IsRepeated);
Assert.IsFalse(singleField.IsRequired);
Assert.IsFalse(singleField.IsRepeated);
Assert.IsFalse(repeatedField.IsRequired);
Assert.IsTrue(repeatedField.IsRepeated);
}
[Test]
public void FieldDescriptorDefault()
{
MessageDescriptor d = TestAllTypes.Descriptor;
Assert.IsFalse(d.FindDescriptor<FieldDescriptor>("optional_int32").HasDefaultValue);
Assert.AreEqual(0, d.FindDescriptor<FieldDescriptor>("optional_int32").DefaultValue);
Assert.IsTrue(d.FindDescriptor<FieldDescriptor>("default_int32").HasDefaultValue);
Assert.AreEqual(41, d.FindDescriptor<FieldDescriptor>("default_int32").DefaultValue);
d = TestExtremeDefaultValues.Descriptor;
Assert.AreEqual(TestExtremeDefaultValues.DefaultInstance.EscapedBytes,
d.FindDescriptor<FieldDescriptor>("escaped_bytes").DefaultValue);
Assert.AreEqual(uint.MaxValue, d.FindDescriptor<FieldDescriptor>("large_uint32").DefaultValue);
Assert.AreEqual(ulong.MaxValue, d.FindDescriptor<FieldDescriptor>("large_uint64").DefaultValue);
}
[Test]
public void EnumDescriptor()
{
// Note: this test is a bit different to the Java version because there's no static way of getting to the descriptor
EnumDescriptor enumType = Unittest.Descriptor.FindTypeByName<EnumDescriptor>("ForeignEnum");
EnumDescriptor enumType = UnittestProto3.Descriptor.FindTypeByName<EnumDescriptor>("ForeignEnum");
EnumDescriptor nestedType = TestAllTypes.Descriptor.FindDescriptor<EnumDescriptor>("NestedEnum");
Assert.AreEqual("ForeignEnum", enumType.Name);
Assert.AreEqual("protobuf_unittest.ForeignEnum", enumType.FullName);
Assert.AreEqual(Unittest.Descriptor, enumType.File);
Assert.AreEqual(UnittestProto3.Descriptor, enumType.File);
Assert.Null(enumType.ContainingType);
Assert.AreEqual(DescriptorProtos.EnumOptions.DefaultInstance,
enumType.Options);
Assert.Null(enumType.Options);
Assert.AreEqual("NestedEnum", nestedType.Name);
Assert.AreEqual("protobuf_unittest.TestAllTypes.NestedEnum",
nestedType.FullName);
Assert.AreEqual(Unittest.Descriptor, nestedType.File);
Assert.AreEqual(UnittestProto3.Descriptor, nestedType.File);
Assert.AreEqual(TestAllTypes.Descriptor, nestedType.ContainingType);
EnumValueDescriptor value = enumType.FindValueByName("FOREIGN_FOO");
Assert.AreEqual(value, enumType.Values[0]);
Assert.AreEqual(value, enumType.Values[1]);
Assert.AreEqual("FOREIGN_FOO", value.Name);
Assert.AreEqual(4, value.Number);
Assert.AreEqual((int) ForeignEnum.FOREIGN_FOO, value.Number);
@ -265,22 +206,5 @@ namespace Google.ProtocolBuffers
Assert.AreEqual(i, enumType.Values[i].Index);
}
}
[Test]
public void CustomOptions()
{
MessageDescriptor descriptor = TestMessageWithCustomOptions.Descriptor;
Assert.IsTrue(descriptor.Options.HasExtension(UnittestCustomOptions.MessageOpt1));
Assert.AreEqual(-56, descriptor.Options.GetExtension(UnittestCustomOptions.MessageOpt1));
FieldDescriptor field = descriptor.FindFieldByName("field1");
Assert.NotNull(field);
Assert.IsTrue(field.Options.HasExtension(UnittestCustomOptions.FieldOpt1));
Assert.AreEqual(8765432109uL, field.Options.GetExtension(UnittestCustomOptions.FieldOpt1));
}
}
}

@ -1,276 +0,0 @@
#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.Collections.Generic;
using Google.ProtocolBuffers.Descriptors;
using Google.ProtocolBuffers.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers
{
public class DynamicMessageTest
{
private ReflectionTester reflectionTester;
private ReflectionTester extensionsReflectionTester;
private ReflectionTester packedReflectionTester;
public DynamicMessageTest()
{
reflectionTester = ReflectionTester.CreateTestAllTypesInstance();
extensionsReflectionTester = ReflectionTester.CreateTestAllExtensionsInstance();
packedReflectionTester = ReflectionTester.CreateTestPackedTypesInstance();
}
[Test]
public void DynamicMessageAccessors()
{
IBuilder builder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor);
reflectionTester.SetAllFieldsViaReflection(builder);
IMessage message = builder.WeakBuild();
reflectionTester.AssertAllFieldsSetViaReflection(message);
}
[Test]
public void DoubleBuildError()
{
DynamicMessage.Builder builder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor);
builder.Build();
Assert.Throws<InvalidOperationException>(() => builder.Build());
}
[Test]
public void DynamicMessageSettersRejectNull()
{
IBuilder builder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor);
reflectionTester.AssertReflectionSettersRejectNull(builder);
}
[Test]
public void DynamicMessageExtensionAccessors()
{
// We don't need to extensively test DynamicMessage's handling of
// extensions because, frankly, it doesn't do anything special with them.
// It treats them just like any other fields.
IBuilder builder = DynamicMessage.CreateBuilder(TestAllExtensions.Descriptor);
extensionsReflectionTester.SetAllFieldsViaReflection(builder);
IMessage message = builder.WeakBuild();
extensionsReflectionTester.AssertAllFieldsSetViaReflection(message);
}
[Test]
public void DynamicMessageExtensionSettersRejectNull()
{
IBuilder builder = DynamicMessage.CreateBuilder(TestAllExtensions.Descriptor);
extensionsReflectionTester.AssertReflectionSettersRejectNull(builder);
}
[Test]
public void DynamicMessageRepeatedSetters()
{
IBuilder builder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor);
reflectionTester.SetAllFieldsViaReflection(builder);
reflectionTester.ModifyRepeatedFieldsViaReflection(builder);
IMessage message = builder.WeakBuild();
reflectionTester.AssertRepeatedFieldsModifiedViaReflection(message);
}
[Test]
public void DynamicMessageRepeatedSettersRejectNull()
{
IBuilder builder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor);
reflectionTester.AssertReflectionRepeatedSettersRejectNull(builder);
}
[Test]
public void DynamicMessageDefaults()
{
reflectionTester.AssertClearViaReflection(DynamicMessage.GetDefaultInstance(TestAllTypes.Descriptor));
reflectionTester.AssertClearViaReflection(DynamicMessage.CreateBuilder(TestAllTypes.Descriptor).Build());
}
[Test]
public void DynamicMessageSerializedSize()
{
TestAllTypes message = TestUtil.GetAllSet();
IBuilder dynamicBuilder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor);
reflectionTester.SetAllFieldsViaReflection(dynamicBuilder);
IMessage dynamicMessage = dynamicBuilder.WeakBuild();
Assert.AreEqual(message.SerializedSize, dynamicMessage.SerializedSize);
}
[Test]
public void DynamicMessageSerialization()
{
IBuilder builder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor);
reflectionTester.SetAllFieldsViaReflection(builder);
IMessage message = builder.WeakBuild();
ByteString rawBytes = message.ToByteString();
TestAllTypes message2 = TestAllTypes.ParseFrom(rawBytes);
TestUtil.AssertAllFieldsSet(message2);
// In fact, the serialized forms should be exactly the same, byte-for-byte.
Assert.AreEqual(TestUtil.GetAllSet().ToByteString(), rawBytes);
}
[Test]
public void DynamicMessageParsing()
{
TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
TestUtil.SetAllFields(builder);
TestAllTypes message = builder.Build();
ByteString rawBytes = message.ToByteString();
IMessage message2 = DynamicMessage.ParseFrom(TestAllTypes.Descriptor, rawBytes);
reflectionTester.AssertAllFieldsSetViaReflection(message2);
}
[Test]
public void DynamicMessagePackedSerialization()
{
IBuilder builder = DynamicMessage.CreateBuilder(TestPackedTypes.Descriptor);
packedReflectionTester.SetPackedFieldsViaReflection(builder);
IMessage message = builder.WeakBuild();
ByteString rawBytes = message.ToByteString();
TestPackedTypes message2 = TestPackedTypes.ParseFrom(rawBytes);
TestUtil.AssertPackedFieldsSet(message2);
// In fact, the serialized forms should be exactly the same, byte-for-byte.
Assert.AreEqual(TestUtil.GetPackedSet().ToByteString(), rawBytes);
}
[Test]
public void DynamicMessagePackedParsing()
{
TestPackedTypes.Builder builder = TestPackedTypes.CreateBuilder();
TestUtil.SetPackedFields(builder);
TestPackedTypes message = builder.Build();
ByteString rawBytes = message.ToByteString();
IMessage message2 = DynamicMessage.ParseFrom(TestPackedTypes.Descriptor, rawBytes);
packedReflectionTester.AssertPackedFieldsSetViaReflection(message2);
}
[Test]
public void DynamicMessageCopy()
{
TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
TestUtil.SetAllFields(builder);
TestAllTypes message = builder.Build();
DynamicMessage copy = DynamicMessage.CreateBuilder(message).Build();
reflectionTester.AssertAllFieldsSetViaReflection(copy);
// Oneof
FieldDescriptor bytesField =
TestAllTypes.Descriptor.FindFieldByName("oneof_bytes");
FieldDescriptor uint32Field =
TestAllTypes.Descriptor.FindFieldByName("oneof_uint32");
Assert.True(copy.HasField(bytesField));
Assert.False(copy.HasField(uint32Field));
DynamicMessage.Builder dynamicBuilder = DynamicMessage.CreateBuilder(message);
dynamicBuilder[uint32Field] = 123U;
DynamicMessage copy2 = dynamicBuilder.Build();
Assert.IsFalse(copy2.HasField(bytesField));
Assert.IsTrue(copy2.HasField(uint32Field));
Assert.AreEqual(123U, copy2[uint32Field]);
}
[Test]
public void ToBuilder()
{
DynamicMessage.Builder builder =
DynamicMessage.CreateBuilder(TestAllTypes.Descriptor);
reflectionTester.SetAllFieldsViaReflection(builder);
int unknownFieldNum = 9;
ulong unknownFieldVal = 90;
builder.SetUnknownFields(UnknownFieldSet.CreateBuilder()
.AddField(unknownFieldNum,
UnknownField.CreateBuilder().AddVarint(unknownFieldVal).Build())
.Build());
DynamicMessage message = builder.Build();
DynamicMessage derived = message.ToBuilder().Build();
reflectionTester.AssertAllFieldsSetViaReflection(derived);
IList<ulong> values = derived.UnknownFields.FieldDictionary[unknownFieldNum].VarintList;
Assert.AreEqual(1, values.Count);
Assert.AreEqual(unknownFieldVal, values[0]);
}
[Test]
public void DynamicOneofMessage()
{
DynamicMessage.Builder builder =
DynamicMessage.CreateBuilder(TestAllTypes.Descriptor);
OneofDescriptor oneof = TestAllTypes.Descriptor.Oneofs[0];
Assert.False(builder.HasOneof(oneof));
Assert.AreSame(null, builder.OneofFieldDescriptor(oneof));
reflectionTester.SetAllFieldsViaReflection(builder);
Assert.True(builder.HasOneof(oneof));
FieldDescriptor field = oneof.Field(3);
Assert.AreSame(field, builder.OneofFieldDescriptor(oneof));
Assert.AreEqual(TestUtil.ToBytes("604"), builder[field]);
DynamicMessage message = builder.BuildPartial();
Assert.IsTrue(message.HasOneof(oneof));
DynamicMessage.Builder mergedBuilder =
DynamicMessage.CreateBuilder(TestAllTypes.Descriptor);
FieldDescriptor mergedField = oneof.Field(0);
mergedBuilder[mergedField] = 123U;
Assert.IsTrue(mergedBuilder.HasField(mergedField));
mergedBuilder.MergeFrom(message);
Assert.IsTrue(mergedBuilder.HasField(field));
Assert.IsFalse(mergedBuilder.HasField(mergedField));
mergedBuilder.ClearOneof(oneof);
Assert.AreSame(null, mergedBuilder.OneofFieldDescriptor(oneof));
message = mergedBuilder.Build();
Assert.AreSame(null, message.OneofFieldDescriptor(oneof));
}
}
}

@ -1,200 +0,0 @@
#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 Google.ProtocolBuffers.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers
{
public class ExtendableMessageTest
{
[Test]
public void ExtensionWriterInvalidExtension()
{
Assert.Throws<ArgumentException>(() =>
TestPackedExtensions.CreateBuilder()[Unittest.OptionalForeignMessageExtension.Descriptor] =
ForeignMessage.DefaultInstance);
}
[Test]
public void ExtensionWriterTest()
{
TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder()
.SetExtension(Unittest.DefaultBoolExtension, true)
.SetExtension(Unittest.DefaultBytesExtension, ByteString.CopyFromUtf8("123"))
.SetExtension(Unittest.DefaultCordExtension, "123")
.SetExtension(Unittest.DefaultDoubleExtension, 123)
.SetExtension(Unittest.DefaultFixed32Extension, 123u)
.SetExtension(Unittest.DefaultFixed64Extension, 123u)
.SetExtension(Unittest.DefaultFloatExtension, 123)
.SetExtension(Unittest.DefaultForeignEnumExtension, ForeignEnum.FOREIGN_BAZ)
.SetExtension(Unittest.DefaultImportEnumExtension, ImportEnum.IMPORT_BAZ)
.SetExtension(Unittest.DefaultInt32Extension, 123)
.SetExtension(Unittest.DefaultInt64Extension, 123)
.SetExtension(Unittest.DefaultNestedEnumExtension, TestAllTypes.Types.NestedEnum.FOO)
.SetExtension(Unittest.DefaultSfixed32Extension, 123)
.SetExtension(Unittest.DefaultSfixed64Extension, 123)
.SetExtension(Unittest.DefaultSint32Extension, 123)
.SetExtension(Unittest.DefaultSint64Extension, 123)
.SetExtension(Unittest.DefaultStringExtension, "123")
.SetExtension(Unittest.DefaultStringPieceExtension, "123")
.SetExtension(Unittest.DefaultUint32Extension, 123u)
.SetExtension(Unittest.DefaultUint64Extension, 123u)
//Optional
.SetExtension(Unittest.OptionalBoolExtension, true)
.SetExtension(Unittest.OptionalBytesExtension, ByteString.CopyFromUtf8("123"))
.SetExtension(Unittest.OptionalCordExtension, "123")
.SetExtension(Unittest.OptionalDoubleExtension, 123)
.SetExtension(Unittest.OptionalFixed32Extension, 123u)
.SetExtension(Unittest.OptionalFixed64Extension, 123u)
.SetExtension(Unittest.OptionalFloatExtension, 123)
.SetExtension(Unittest.OptionalForeignEnumExtension, ForeignEnum.FOREIGN_BAZ)
.SetExtension(Unittest.OptionalImportEnumExtension, ImportEnum.IMPORT_BAZ)
.SetExtension(Unittest.OptionalInt32Extension, 123)
.SetExtension(Unittest.OptionalInt64Extension, 123)
.SetExtension(Unittest.OptionalNestedEnumExtension, TestAllTypes.Types.NestedEnum.FOO)
.SetExtension(Unittest.OptionalSfixed32Extension, 123)
.SetExtension(Unittest.OptionalSfixed64Extension, 123)
.SetExtension(Unittest.OptionalSint32Extension, 123)
.SetExtension(Unittest.OptionalSint64Extension, 123)
.SetExtension(Unittest.OptionalStringExtension, "123")
.SetExtension(Unittest.OptionalStringPieceExtension, "123")
.SetExtension(Unittest.OptionalUint32Extension, 123u)
.SetExtension(Unittest.OptionalUint64Extension, 123u)
//Repeated
.AddExtension(Unittest.RepeatedBoolExtension, true)
.AddExtension(Unittest.RepeatedBytesExtension, ByteString.CopyFromUtf8("123"))
.AddExtension(Unittest.RepeatedCordExtension, "123")
.AddExtension(Unittest.RepeatedDoubleExtension, 123)
.AddExtension(Unittest.RepeatedFixed32Extension, 123u)
.AddExtension(Unittest.RepeatedFixed64Extension, 123u)
.AddExtension(Unittest.RepeatedFloatExtension, 123)
.AddExtension(Unittest.RepeatedForeignEnumExtension, ForeignEnum.FOREIGN_BAZ)
.AddExtension(Unittest.RepeatedImportEnumExtension, ImportEnum.IMPORT_BAZ)
.AddExtension(Unittest.RepeatedInt32Extension, 123)
.AddExtension(Unittest.RepeatedInt64Extension, 123)
.AddExtension(Unittest.RepeatedNestedEnumExtension, TestAllTypes.Types.NestedEnum.FOO)
.AddExtension(Unittest.RepeatedSfixed32Extension, 123)
.AddExtension(Unittest.RepeatedSfixed64Extension, 123)
.AddExtension(Unittest.RepeatedSint32Extension, 123)
.AddExtension(Unittest.RepeatedSint64Extension, 123)
.AddExtension(Unittest.RepeatedStringExtension, "123")
.AddExtension(Unittest.RepeatedStringPieceExtension, "123")
.AddExtension(Unittest.RepeatedUint32Extension, 123u)
.AddExtension(Unittest.RepeatedUint64Extension, 123u)
;
TestAllExtensions msg = builder.Build();
ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
Unittest.RegisterAllExtensions(registry);
TestAllExtensions.Builder copyBuilder = TestAllExtensions.CreateBuilder().MergeFrom(msg.ToByteArray(),
registry);
TestAllExtensions copy = copyBuilder.Build();
Assert.AreEqual(msg.ToByteArray(), copy.ToByteArray());
Assert.AreEqual(true, copy.GetExtension(Unittest.DefaultBoolExtension));
Assert.AreEqual(ByteString.CopyFromUtf8("123"), copy.GetExtension(Unittest.DefaultBytesExtension));
Assert.AreEqual("123", copy.GetExtension(Unittest.DefaultCordExtension));
Assert.AreEqual(123, copy.GetExtension(Unittest.DefaultDoubleExtension));
Assert.AreEqual(123u, copy.GetExtension(Unittest.DefaultFixed32Extension));
Assert.AreEqual(123u, copy.GetExtension(Unittest.DefaultFixed64Extension));
Assert.AreEqual(123, copy.GetExtension(Unittest.DefaultFloatExtension));
Assert.AreEqual(ForeignEnum.FOREIGN_BAZ, copy.GetExtension(Unittest.DefaultForeignEnumExtension));
Assert.AreEqual(ImportEnum.IMPORT_BAZ, copy.GetExtension(Unittest.DefaultImportEnumExtension));
Assert.AreEqual(123, copy.GetExtension(Unittest.DefaultInt32Extension));
Assert.AreEqual(123, copy.GetExtension(Unittest.DefaultInt64Extension));
Assert.AreEqual(TestAllTypes.Types.NestedEnum.FOO,
copy.GetExtension(Unittest.DefaultNestedEnumExtension));
Assert.AreEqual(123, copy.GetExtension(Unittest.DefaultSfixed32Extension));
Assert.AreEqual(123, copy.GetExtension(Unittest.DefaultSfixed64Extension));
Assert.AreEqual(123, copy.GetExtension(Unittest.DefaultSint32Extension));
Assert.AreEqual(123, copy.GetExtension(Unittest.DefaultSint64Extension));
Assert.AreEqual("123", copy.GetExtension(Unittest.DefaultStringExtension));
Assert.AreEqual("123", copy.GetExtension(Unittest.DefaultStringPieceExtension));
Assert.AreEqual(123u, copy.GetExtension(Unittest.DefaultUint32Extension));
Assert.AreEqual(123u, copy.GetExtension(Unittest.DefaultUint64Extension));
Assert.AreEqual(true, copy.GetExtension(Unittest.OptionalBoolExtension));
Assert.AreEqual(ByteString.CopyFromUtf8("123"), copy.GetExtension(Unittest.OptionalBytesExtension));
Assert.AreEqual("123", copy.GetExtension(Unittest.OptionalCordExtension));
Assert.AreEqual(123, copy.GetExtension(Unittest.OptionalDoubleExtension));
Assert.AreEqual(123u, copy.GetExtension(Unittest.OptionalFixed32Extension));
Assert.AreEqual(123u, copy.GetExtension(Unittest.OptionalFixed64Extension));
Assert.AreEqual(123, copy.GetExtension(Unittest.OptionalFloatExtension));
Assert.AreEqual(ForeignEnum.FOREIGN_BAZ, copy.GetExtension(Unittest.OptionalForeignEnumExtension));
Assert.AreEqual(ImportEnum.IMPORT_BAZ, copy.GetExtension(Unittest.OptionalImportEnumExtension));
Assert.AreEqual(123, copy.GetExtension(Unittest.OptionalInt32Extension));
Assert.AreEqual(123, copy.GetExtension(Unittest.OptionalInt64Extension));
Assert.AreEqual(TestAllTypes.Types.NestedEnum.FOO,
copy.GetExtension(Unittest.OptionalNestedEnumExtension));
Assert.AreEqual(123, copy.GetExtension(Unittest.OptionalSfixed32Extension));
Assert.AreEqual(123, copy.GetExtension(Unittest.OptionalSfixed64Extension));
Assert.AreEqual(123, copy.GetExtension(Unittest.OptionalSint32Extension));
Assert.AreEqual(123, copy.GetExtension(Unittest.OptionalSint64Extension));
Assert.AreEqual("123", copy.GetExtension(Unittest.OptionalStringExtension));
Assert.AreEqual("123", copy.GetExtension(Unittest.OptionalStringPieceExtension));
Assert.AreEqual(123u, copy.GetExtension(Unittest.OptionalUint32Extension));
Assert.AreEqual(123u, copy.GetExtension(Unittest.OptionalUint64Extension));
Assert.AreEqual(true, copy.GetExtension(Unittest.RepeatedBoolExtension, 0));
Assert.AreEqual(ByteString.CopyFromUtf8("123"),
copy.GetExtension(Unittest.RepeatedBytesExtension, 0));
Assert.AreEqual("123", copy.GetExtension(Unittest.RepeatedCordExtension, 0));
Assert.AreEqual(123, copy.GetExtension(Unittest.RepeatedDoubleExtension, 0));
Assert.AreEqual(123u, copy.GetExtension(Unittest.RepeatedFixed32Extension, 0));
Assert.AreEqual(123u, copy.GetExtension(Unittest.RepeatedFixed64Extension, 0));
Assert.AreEqual(123, copy.GetExtension(Unittest.RepeatedFloatExtension, 0));
Assert.AreEqual(ForeignEnum.FOREIGN_BAZ,
copy.GetExtension(Unittest.RepeatedForeignEnumExtension, 0));
Assert.AreEqual(ImportEnum.IMPORT_BAZ, copy.GetExtension(Unittest.RepeatedImportEnumExtension, 0));
Assert.AreEqual(123, copy.GetExtension(Unittest.RepeatedInt32Extension, 0));
Assert.AreEqual(123, copy.GetExtension(Unittest.RepeatedInt64Extension, 0));
Assert.AreEqual(TestAllTypes.Types.NestedEnum.FOO,
copy.GetExtension(Unittest.RepeatedNestedEnumExtension, 0));
Assert.AreEqual(123, copy.GetExtension(Unittest.RepeatedSfixed32Extension, 0));
Assert.AreEqual(123, copy.GetExtension(Unittest.RepeatedSfixed64Extension, 0));
Assert.AreEqual(123, copy.GetExtension(Unittest.RepeatedSint32Extension, 0));
Assert.AreEqual(123, copy.GetExtension(Unittest.RepeatedSint64Extension, 0));
Assert.AreEqual("123", copy.GetExtension(Unittest.RepeatedStringExtension, 0));
Assert.AreEqual("123", copy.GetExtension(Unittest.RepeatedStringPieceExtension, 0));
Assert.AreEqual(123u, copy.GetExtension(Unittest.RepeatedUint32Extension, 0));
Assert.AreEqual(123u, copy.GetExtension(Unittest.RepeatedUint64Extension, 0));
}
}
}

@ -1,198 +0,0 @@
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2015 Google Inc. All rights reserved.
// Author: jieluo@google.com (Jie Luo)
//
// 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
// 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 Google.ProtocolBuffers.Descriptors;
using Google.ProtocolBuffers.TestProtos.Proto3;
using NUnit.Framework;
namespace Google.ProtocolBuffers
{
public class FieldPresenceTest
{
private void CheckHasMethodRemoved(Type proto2Type, Type proto3Type, string name)
{
Assert.NotNull(proto2Type.GetProperty(name));
Assert.NotNull(proto2Type.GetProperty("Has" + name));
Assert.NotNull(proto3Type.GetProperty(name));
Assert.Null(proto3Type.GetProperty("Has" + name));
}
[Test]
public void TestHasMethod()
{
// Optional non-message fields don't have HasFoo method generated
Type proto2Type = typeof(Google.ProtocolBuffers.TestProtos.TestAllTypes);
Type proto3Type = typeof(TestAllTypes);
CheckHasMethodRemoved(proto2Type, proto3Type, "OptionalInt32");
CheckHasMethodRemoved(proto2Type, proto3Type, "OptionalString");
CheckHasMethodRemoved(proto2Type, proto3Type, "OptionalBytes");
CheckHasMethodRemoved(proto2Type, proto3Type, "OptionalNestedEnum");
Type proto2BuilderType = typeof(Google.ProtocolBuffers.TestProtos.TestAllTypes.Builder);
Type proto3BuilderType = typeof(TestAllTypes.Builder);
CheckHasMethodRemoved(proto2BuilderType, proto3BuilderType, "OptionalInt32");
CheckHasMethodRemoved(proto2BuilderType, proto3BuilderType, "OptionalString");
CheckHasMethodRemoved(proto2BuilderType, proto3BuilderType, "OptionalBytes");
CheckHasMethodRemoved(proto2BuilderType, proto3BuilderType, "OptionalNestedEnum");
// message fields still have the HasFoo method generated
Assert.IsFalse(TestAllTypes.CreateBuilder().Build().HasOptionalNestedMessage);
Assert.IsFalse(TestAllTypes.CreateBuilder().HasOptionalNestedMessage);
// oneof fields don't have the HasFoo method (even for message types)
CheckHasMethodRemoved(proto2Type, proto3Type, "OneofUint32");
CheckHasMethodRemoved(proto2Type, proto3Type, "OneofString");
CheckHasMethodRemoved(proto2Type, proto3Type, "OneofNestedMessage");
CheckHasMethodRemoved(proto2BuilderType, proto3BuilderType, "OneofUint32");
CheckHasMethodRemoved(proto2BuilderType, proto3BuilderType, "OneofString");
CheckHasMethodRemoved(proto2BuilderType, proto3BuilderType, "OneofNestedMessage");
}
[Test]
public void TestFieldPresence()
{
// Optional non-message fields set to their default value are treated the same
// way as not set.
// Serialization will ignore such fields.
TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
builder.SetOptionalInt32(0);
builder.SetOptionalString("");
builder.SetOptionalBytes(ByteString.Empty);
builder.SetOptionalNestedEnum(TestAllTypes.Types.NestedEnum.FOO);
TestAllTypes message = builder.Build();
Assert.AreEqual(0, message.SerializedSize);
// Test merge
TestAllTypes.Builder a = TestAllTypes.CreateBuilder();
a.SetOptionalInt32(1);
a.SetOptionalString("x");
a.SetOptionalBytes(ByteString.CopyFromUtf8("y"));
a.SetOptionalNestedEnum(TestAllTypes.Types.NestedEnum.BAR);
a.MergeFrom(message);
TestAllTypes messageA = a.Build();
Assert.AreEqual(1, messageA.OptionalInt32);
Assert.AreEqual("x", messageA.OptionalString);
Assert.AreEqual(ByteString.CopyFromUtf8("y"), messageA.OptionalBytes);
Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAR, messageA.OptionalNestedEnum);
// equals/hashCode should produce the same results
TestAllTypes empty = TestAllTypes.CreateBuilder().Build();
Assert.IsTrue(empty.Equals(message));
Assert.IsTrue(message.Equals(empty));
Assert.AreEqual(empty.GetHashCode(), message.GetHashCode());
}
[Test]
public void TestFieldPresenceReflection()
{
MessageDescriptor descriptor = TestAllTypes.Descriptor;
FieldDescriptor optionalInt32Field = descriptor.FindFieldByName("optional_int32");
FieldDescriptor optionalStringField = descriptor.FindFieldByName("optional_string");
FieldDescriptor optionalBytesField = descriptor.FindFieldByName("optional_bytes");
FieldDescriptor optionalNestedEnumField = descriptor.FindFieldByName("optional_nested_enum");
FieldDescriptor oneofUint32Field = descriptor.FindFieldByName("oneof_uint32");
TestAllTypes message = TestAllTypes.CreateBuilder().Build();
Assert.IsFalse(message.HasField(optionalInt32Field));
Assert.IsFalse(message.HasField(optionalStringField));
Assert.IsFalse(message.HasField(optionalBytesField));
Assert.IsFalse(message.HasField(optionalNestedEnumField));
// Set to default value is seen as not present for optional fields.
// Set to default value is seen as present for oneof fields.
message = TestAllTypes.CreateBuilder()
.SetOptionalInt32(0)
.SetOptionalString("")
.SetOptionalBytes(ByteString.Empty)
.SetOptionalNestedEnum(TestAllTypes.Types.NestedEnum.FOO)
.SetOneofUint32(0U)
.Build();
Assert.IsFalse(message.HasField(optionalInt32Field));
Assert.IsFalse(message.HasField(optionalStringField));
Assert.IsFalse(message.HasField(optionalBytesField));
Assert.IsFalse(message.HasField(optionalNestedEnumField));
Assert.IsTrue(message.HasField(oneofUint32Field));
Assert.AreEqual(1, message.AllFields.Count);
// Set to non-defalut value is seen as present
message = TestAllTypes.CreateBuilder()
.SetOptionalInt32(1)
.SetOptionalString("x")
.SetOptionalBytes(ByteString.CopyFromUtf8("y"))
.SetOptionalNestedEnum(TestAllTypes.Types.NestedEnum.BAR)
.Build();
Assert.IsTrue(message.HasField(optionalInt32Field));
Assert.IsTrue(message.HasField(optionalStringField));
Assert.IsTrue(message.HasField(optionalBytesField));
Assert.IsTrue(message.HasField(optionalNestedEnumField));
Assert.AreEqual(4, message.AllFields.Count);
}
[Test]
public void TestMessageField()
{
TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
Assert.IsFalse(builder.HasOptionalNestedMessage);
Assert.IsFalse(builder.Build().HasOptionalNestedMessage);
// Unlike non-message fields, if we set default value to message field, the field
// shoule be seem as present.
builder.SetOptionalNestedMessage(TestAllTypes.Types.NestedMessage.DefaultInstance);
Assert.IsTrue(builder.HasOptionalNestedMessage);
Assert.IsTrue(builder.Build().HasOptionalNestedMessage);
}
[Test]
public void TestSerializeAndParse()
{
TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
builder.SetOptionalInt32(1234);
builder.SetOptionalString("hello");
builder.SetOptionalNestedMessage(TestAllTypes.Types.NestedMessage.DefaultInstance);
builder.SetOneofUint32(0U);
ByteString data = builder.Build().ToByteString();
TestAllTypes message = TestAllTypes.ParseFrom(data);
Assert.AreEqual(1234, message.OptionalInt32);
Assert.AreEqual("hello", message.OptionalString);
Assert.AreEqual(ByteString.Empty, message.OptionalBytes);
Assert.AreEqual(TestAllTypes.Types.NestedEnum.FOO, message.OptionalNestedEnum);
Assert.IsTrue(message.HasOptionalNestedMessage);
Assert.AreEqual(0, message.OptionalNestedMessage.Bb);
Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, message.OneofFieldCase);
}
}
}

@ -1,102 +0,0 @@
using System;
using System.Collections.Generic;
using Google.ProtocolBuffers.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers
{
public class GeneratedBuilderTest
{
class OneTimeEnumerator<T> : IEnumerable<T>
{
readonly T _item;
bool _enumerated;
public OneTimeEnumerator(T item)
{
_item = item;
}
public IEnumerator<T> GetEnumerator()
{
Assert.IsFalse(_enumerated);
_enumerated = true;
yield return _item;
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
[Test]
public void DoesNotEnumerateTwiceForMessageList()
{
TestAllTypes.Builder b = new TestAllTypes.Builder();
b.AddRangeRepeatedForeignMessage(new OneTimeEnumerator<ForeignMessage>(ForeignMessage.DefaultInstance));
}
[Test]
public void DoesNotEnumerateTwiceForPrimitiveList()
{
TestAllTypes.Builder b = new TestAllTypes.Builder();
b.AddRangeRepeatedInt32(new OneTimeEnumerator<int>(1));
}
[Test]
public void DoesNotEnumerateTwiceForStringList()
{
TestAllTypes.Builder b = new TestAllTypes.Builder();
b.AddRangeRepeatedString(new OneTimeEnumerator<string>("test"));
}
[Test]
public void DoesNotEnumerateTwiceForEnumList()
{
TestAllTypes.Builder b = new TestAllTypes.Builder();
b.AddRangeRepeatedForeignEnum(new OneTimeEnumerator<ForeignEnum>(ForeignEnum.FOREIGN_BAR));
}
[Test]
public void DoesNotAddNullToMessageListByAddRange()
{
TestAllTypes.Builder b = new TestAllTypes.Builder();
Assert.Throws<ArgumentNullException>(() => b.AddRangeRepeatedForeignMessage(new ForeignMessage[] { null }));
}
[Test]
public void DoesNotAddNullToMessageListByAdd()
{
TestAllTypes.Builder b = new TestAllTypes.Builder();
Assert.Throws<ArgumentNullException>(() => b.AddRepeatedForeignMessage((ForeignMessage)null));
}
[Test]
public void DoesNotAddNullToMessageListBySet()
{
TestAllTypes.Builder b = new TestAllTypes.Builder();
b.AddRepeatedForeignMessage(ForeignMessage.DefaultInstance);
Assert.Throws<ArgumentNullException>(() => b.SetRepeatedForeignMessage(0, (ForeignMessage)null));
}
[Test]
public void DoesNotAddNullToStringListByAddRange()
{
TestAllTypes.Builder b = new TestAllTypes.Builder();
Assert.Throws<ArgumentNullException>(() => b.AddRangeRepeatedString(new String[] { null }));
}
[Test]
public void DoesNotAddNullToStringListByAdd()
{
TestAllTypes.Builder b = new TestAllTypes.Builder();
Assert.Throws<ArgumentNullException>(() => b.AddRepeatedString(null));
}
[Test]
public void DoesNotAddNullToStringListBySet()
{
TestAllTypes.Builder b = new TestAllTypes.Builder();
b.AddRepeatedString("one");
Assert.Throws<ArgumentNullException>(() => b.SetRepeatedString(0, null));
}
}
}

@ -1,776 +1,153 @@
#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;
using System.Collections.Generic;
using Google.ProtocolBuffers.Descriptors;
using Google.ProtocolBuffers.Collections;
using Google.ProtocolBuffers.TestProtos;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Google.Protobuf.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers
namespace Google.Protobuf
{
/// <summary>
/// Tests around the generated TestAllTypes message.
/// </summary>
public class GeneratedMessageTest
{
private readonly ReflectionTester reflectionTester;
private readonly ReflectionTester extensionsReflectionTester;
public GeneratedMessageTest()
{
reflectionTester = ReflectionTester.CreateTestAllTypesInstance();
extensionsReflectionTester = ReflectionTester.CreateTestAllExtensionsInstance();
}
[Test]
public void RepeatedAddPrimitiveBeforeBuild()
{
TestAllTypes message = new TestAllTypes.Builder {RepeatedInt32List = {1, 2, 3}}.Build();
TestUtil.AssertEqual(new int[] {1, 2, 3}, message.RepeatedInt32List);
}
[Test]
public void AddPrimitiveFailsAfterBuild()
{
TestAllTypes.Builder builder = new TestAllTypes.Builder();
IList<int> list = builder.RepeatedInt32List;
list.Add(1); // Fine
builder.Build();
Assert.Throws<NotSupportedException>(() => list.Add(2));
}
[Test]
public void RepeatedAddMessageBeforeBuild()
{
TestAllTypes message = new TestAllTypes.Builder
{
RepeatedNestedMessageList =
{new TestAllTypes.Types.NestedMessage.Builder {Bb = 10}.Build()}
}.Build();
Assert.AreEqual(1, message.RepeatedNestedMessageCount);
Assert.AreEqual(10, message.RepeatedNestedMessageList[0].Bb);
}
[Test]
public void AddMessageFailsAfterBuild()
{
TestAllTypes.Builder builder = new TestAllTypes.Builder();
IList<TestAllTypes.Types.NestedMessage> list = builder.RepeatedNestedMessageList;
builder.Build();
Assert.Throws<NotSupportedException>(() => list.Add(new TestAllTypes.Types.NestedMessage.Builder { Bb = 10 }.Build()));
}
[Test]
public void DefaultInstance()
{
Assert.AreSame(TestAllTypes.DefaultInstance, TestAllTypes.DefaultInstance.DefaultInstanceForType);
Assert.AreSame(TestAllTypes.DefaultInstance, TestAllTypes.CreateBuilder().DefaultInstanceForType);
}
[Test]
public void Accessors()
{
TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
TestUtil.SetAllFields(builder);
TestAllTypes message = builder.Build();
TestUtil.AssertAllFieldsSet(message);
}
[Test]
public void SettersRejectNull()
{
TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
Assert.Throws<ArgumentNullException>(() => builder.SetOptionalString(null));
Assert.Throws<ArgumentNullException>(() => builder.SetOptionalBytes(null));
Assert.Throws<ArgumentNullException>(
() => builder.SetOptionalNestedMessage((TestAllTypes.Types.NestedMessage) null));
Assert.Throws<ArgumentNullException>(
() => builder.SetOptionalNestedMessage((TestAllTypes.Types.NestedMessage.Builder) null));
Assert.Throws<ArgumentNullException>(() => builder.AddRepeatedString(null));
Assert.Throws<ArgumentNullException>(() => builder.AddRepeatedBytes(null));
Assert.Throws<ArgumentNullException>(
() => builder.AddRepeatedNestedMessage((TestAllTypes.Types.NestedMessage) null));
Assert.Throws<ArgumentNullException>(
() => builder.AddRepeatedNestedMessage((TestAllTypes.Types.NestedMessage.Builder) null));
}
[Test]
public void RepeatedSetters()
{
TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
TestUtil.SetAllFields(builder);
TestUtil.ModifyRepeatedFields(builder);
TestAllTypes message = builder.Build();
TestUtil.AssertRepeatedFieldsModified(message);
}
[Test]
public void RepeatedAppend()
{
TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
builder.AddRangeRepeatedInt32(new int[] {1, 2, 3, 4});
builder.AddRangeRepeatedForeignEnum((new ForeignEnum[] {ForeignEnum.FOREIGN_BAZ}));
ForeignMessage foreignMessage = ForeignMessage.CreateBuilder().SetC(12).Build();
builder.AddRangeRepeatedForeignMessage(new ForeignMessage[] {foreignMessage});
TestAllTypes message = builder.Build();
TestUtil.AssertEqual(message.RepeatedInt32List, new int[] {1, 2, 3, 4});
TestUtil.AssertEqual(message.RepeatedForeignEnumList, new ForeignEnum[] {ForeignEnum.FOREIGN_BAZ});
Assert.AreEqual(1, message.RepeatedForeignMessageCount);
Assert.AreEqual(12, message.GetRepeatedForeignMessage(0).C);
}
[Test]
public void RepeatedAppendRejectsNull()
{
TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
ForeignMessage foreignMessage = ForeignMessage.CreateBuilder().SetC(12).Build();
Assert.Throws<ArgumentNullException>(
() => builder.AddRangeRepeatedForeignMessage(new[] {foreignMessage, null}));
Assert.Throws<ArgumentNullException>(() => builder.AddRangeRepeatedForeignMessage(null));
Assert.Throws<ArgumentNullException>(() => builder.AddRangeRepeatedForeignEnum(null));
Assert.Throws<ArgumentNullException>(() => builder.AddRangeRepeatedString(new[] {"one", null}));
Assert.Throws<ArgumentNullException>(
() => builder.AddRangeRepeatedBytes(new[] {TestUtil.ToBytes("one"), null}));
}
[Test]
public void SettingForeignMessageUsingBuilder()
{
TestAllTypes message = TestAllTypes.CreateBuilder()
// Pass builder for foreign message instance.
.SetOptionalForeignMessage(ForeignMessage.CreateBuilder().SetC(123))
.Build();
TestAllTypes expectedMessage = TestAllTypes.CreateBuilder()
// Create expected version passing foreign message instance explicitly.
.SetOptionalForeignMessage(ForeignMessage.CreateBuilder().SetC(123).Build())
.Build();
Assert.AreEqual(expectedMessage, message);
}
[Test]
public void SettingRepeatedForeignMessageUsingBuilder()
{
TestAllTypes message = TestAllTypes.CreateBuilder()
// Pass builder for foreign message instance.
.AddRepeatedForeignMessage(ForeignMessage.CreateBuilder().SetC(456))
.Build();
TestAllTypes expectedMessage = TestAllTypes.CreateBuilder()
// Create expected version passing foreign message instance explicitly.
.AddRepeatedForeignMessage(ForeignMessage.CreateBuilder().SetC(456).Build())
.Build();
Assert.AreEqual(expectedMessage, message);
}
[Test]
public void SettingRepeatedValuesUsingRangeInCollectionInitializer()
{
int[] values = {1, 2, 3};
TestAllTypes message = new TestAllTypes.Builder
{
RepeatedSint32List = {values}
}.Build();
Assert.IsTrue(Lists.Equals(values, message.RepeatedSint32List));
}
[Test]
public void SettingRepeatedValuesUsingIndividualValuesInCollectionInitializer()
{
TestAllTypes message = new TestAllTypes.Builder
{
RepeatedSint32List = {6, 7}
}.Build();
Assert.IsTrue(Lists.Equals(new int[] {6, 7}, message.RepeatedSint32List));
}
[Test]
public void Defaults()
{
TestUtil.AssertClear(TestAllTypes.DefaultInstance);
TestUtil.AssertClear(TestAllTypes.CreateBuilder().Build());
Assert.AreEqual("\u1234", TestExtremeDefaultValues.DefaultInstance.Utf8String);
}
[Test]
public void ReflectionGetters()
{
TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
TestUtil.SetAllFields(builder);
TestAllTypes message = builder.Build();
reflectionTester.AssertAllFieldsSetViaReflection(message);
}
[Test]
public void ReflectionSetters()
{
TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
reflectionTester.SetAllFieldsViaReflection(builder);
TestAllTypes message = builder.Build();
TestUtil.AssertAllFieldsSet(message);
}
[Test]
public void ReflectionClear()
{
TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
reflectionTester.SetAllFieldsViaReflection(builder);
reflectionTester.ClearAllFieldsViaReflection(builder);
TestAllTypes message = builder.Build();
TestUtil.AssertClear(message);
}
[Test]
public void ReflectionSettersRejectNull()
{
TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
reflectionTester.AssertReflectionSettersRejectNull(builder);
}
[Test]
public void ReflectionRepeatedSetters()
{
TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
reflectionTester.SetAllFieldsViaReflection(builder);
reflectionTester.ModifyRepeatedFieldsViaReflection(builder);
TestAllTypes message = builder.Build();
TestUtil.AssertRepeatedFieldsModified(message);
}
[Test]
public void TestReflectionRepeatedSettersRejectNull()
{
TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
reflectionTester.AssertReflectionRepeatedSettersRejectNull(builder);
}
[Test]
public void ReflectionDefaults()
{
TestUtil.TestInMultipleCultures(() =>
{
reflectionTester.AssertClearViaReflection(
TestAllTypes.DefaultInstance);
reflectionTester.AssertClearViaReflection(
TestAllTypes.CreateBuilder().Build());
});
}
[Test]
public void ReflectionGetOneof()
{
TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
reflectionTester.SetAllFieldsViaReflection(builder);
Descriptors.OneofDescriptor oneof = TestAllTypes.Descriptor.Oneofs[0];
Descriptors.FieldDescriptor field = TestAllTypes.Descriptor.FindFieldByName("oneof_bytes");
Assert.AreSame(field, builder.OneofFieldDescriptor(oneof));
}
[Test]
public void ReflectionClearOneof()
{
TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
reflectionTester.SetAllFieldsViaReflection(builder);
OneofDescriptor oneof = TestAllTypes.Descriptor.Oneofs[0];
FieldDescriptor field = TestAllTypes.Descriptor.FindFieldByName("oneof_bytes");
Assert.IsTrue(builder.HasOneof(oneof));
Assert.IsTrue(builder.HasField(field));
builder.ClearOneof(oneof);
Assert.IsFalse(builder.HasOneof(oneof));
Assert.IsFalse(builder.HasField(field));
}
// =================================================================
// Extensions.
[Test]
public void ExtensionAccessors()
{
TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder();
TestUtil.SetAllExtensions(builder);
TestAllExtensions message = builder.Build();
TestUtil.AssertAllExtensionsSet(message);
}
[Test]
public void ExtensionRepeatedSetters()
{
TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder();
TestUtil.SetAllExtensions(builder);
TestUtil.ModifyRepeatedExtensions(builder);
TestAllExtensions message = builder.Build();
TestUtil.AssertRepeatedExtensionsModified(message);
}
[Test]
public void ExtensionDefaults()
{
TestUtil.AssertExtensionsClear(TestAllExtensions.DefaultInstance);
TestUtil.AssertExtensionsClear(TestAllExtensions.CreateBuilder().Build());
}
[Test]
public void ExtensionReflectionGetters()
{
TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder();
TestUtil.SetAllExtensions(builder);
TestAllExtensions message = builder.Build();
extensionsReflectionTester.AssertAllFieldsSetViaReflection(message);
}
[Test]
public void ExtensionReflectionSetters()
{
TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder();
extensionsReflectionTester.SetAllFieldsViaReflection(builder);
TestAllExtensions message = builder.Build();
TestUtil.AssertAllExtensionsSet(message);
}
[Test]
public void ExtensionReflectionSettersRejectNull()
{
TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder();
extensionsReflectionTester.AssertReflectionSettersRejectNull(builder);
}
[Test]
public void ExtensionReflectionRepeatedSetters()
{
TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder();
extensionsReflectionTester.SetAllFieldsViaReflection(builder);
extensionsReflectionTester.ModifyRepeatedFieldsViaReflection(builder);
TestAllExtensions message = builder.Build();
TestUtil.AssertRepeatedExtensionsModified(message);
}
[Test]
public void ExtensionReflectionRepeatedSettersRejectNull()
{
TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder();
extensionsReflectionTester.AssertReflectionRepeatedSettersRejectNull(builder);
}
[Test]
public void ExtensionReflectionDefaults()
{
TestUtil.TestInMultipleCultures(() =>
{
extensionsReflectionTester.AssertClearViaReflection(
TestAllExtensions.DefaultInstance);
extensionsReflectionTester.AssertClearViaReflection(
TestAllExtensions.CreateBuilder().Build());
});
}
[Test]
public void ClearExtension()
{
// ClearExtension() is not actually used in TestUtil, so try it manually.
Assert.IsFalse(TestAllExtensions.CreateBuilder()
.SetExtension(Unittest.OptionalInt32Extension, 1)
.ClearExtension(Unittest.OptionalInt32Extension)
.HasExtension(Unittest.OptionalInt32Extension));
Assert.AreEqual(0, TestAllExtensions.CreateBuilder()
.AddExtension(Unittest.RepeatedInt32Extension, 1)
.ClearExtension(Unittest.RepeatedInt32Extension)
.GetExtensionCount(Unittest.RepeatedInt32Extension));
}
[Test]
public void ExtensionMergeFrom()
{
TestAllExtensions original = TestAllExtensions.CreateBuilder()
.SetExtension(Unittest.OptionalInt32Extension, 1).Build();
TestAllExtensions merged =
TestAllExtensions.CreateBuilder().MergeFrom(original).Build();
Assert.IsTrue((merged.HasExtension(Unittest.OptionalInt32Extension)));
Assert.AreEqual(1, (int) merged.GetExtension(Unittest.OptionalInt32Extension));
}
/* Removed multiple files option for the moment
[Test]
public void MultipleFilesOption() {
// We mostly just want to check that things compile.
MessageWithNoOuter message = MessageWithNoOuter.CreateBuilder()
.SetNested(MessageWithNoOuter.Types.NestedMessage.CreateBuilder().SetI(1))
.AddForeign(TestAllTypes.CreateBuilder().SetOptionalInt32(1))
.SetNestedEnum(MessageWithNoOuter.Types.NestedEnum.BAZ)
.SetForeignEnum(EnumWithNoOuter.BAR)
.Build();
Assert.AreEqual(message, MessageWithNoOuter.ParseFrom(message.ToByteString()));
Assert.AreEqual(MultiFileProto.DescriptorProtoFile, MessageWithNoOuter.DescriptorProtoFile.File);
FieldDescriptor field = MessageWithNoOuter.DescriptorProtoFile.FindDescriptor<FieldDescriptor>("foreign_enum");
Assert.AreEqual(MultiFileProto.DescriptorProtoFile.FindTypeByName<EnumDescriptor>("EnumWithNoOuter")
.FindValueByNumber((int)EnumWithNoOuter.BAR), message[field]);
Assert.AreEqual(MultiFileProto.DescriptorProtoFile, ServiceWithNoOuter.DescriptorProtoFile.File);
Assert.IsFalse(TestAllExtensions.DefaultInstance.HasExtension(MultiFileProto.ExtensionWithOuter));
}*/
[Test]
public void OptionalFieldWithRequiredSubfieldsOptimizedForSize()
{
TestOptionalOptimizedForSize message = TestOptionalOptimizedForSize.DefaultInstance;
Assert.IsTrue(message.IsInitialized);
message = TestOptionalOptimizedForSize.CreateBuilder().SetO(
TestRequiredOptimizedForSize.CreateBuilder().BuildPartial()
).BuildPartial();
Assert.IsFalse(message.IsInitialized);
message = TestOptionalOptimizedForSize.CreateBuilder().SetO(
TestRequiredOptimizedForSize.CreateBuilder().SetX(5).BuildPartial()
).BuildPartial();
Assert.IsTrue(message.IsInitialized);
}
[Test]
public void OptimizedForSizeMergeUsesAllFieldsFromTarget()
{
TestOptimizedForSize withFieldSet = new TestOptimizedForSize.Builder {I = 10}.Build();
TestOptimizedForSize.Builder builder = new TestOptimizedForSize.Builder();
builder.MergeFrom(withFieldSet);
TestOptimizedForSize built = builder.Build();
Assert.AreEqual(10, built.I);
}
[Test]
public void UninitializedExtensionInOptimizedForSizeMakesMessageUninitialized()
{
TestOptimizedForSize.Builder builder = new TestOptimizedForSize.Builder();
builder.SetExtension(TestOptimizedForSize.TestExtension2,
new TestRequiredOptimizedForSize.Builder().BuildPartial());
Assert.IsFalse(builder.IsInitialized);
Assert.IsFalse(builder.BuildPartial().IsInitialized);
builder = new TestOptimizedForSize.Builder();
builder.SetExtension(TestOptimizedForSize.TestExtension2,
new TestRequiredOptimizedForSize.Builder {X = 10}.BuildPartial());
Assert.IsTrue(builder.IsInitialized);
Assert.IsTrue(builder.BuildPartial().IsInitialized);
}
[Test]
public void ToBuilder()
{
TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
TestUtil.SetAllFields(builder);
TestAllTypes message = builder.Build();
TestUtil.AssertAllFieldsSet(message.ToBuilder().Build());
}
[Test]
public void FieldConstantValues()
{
Assert.AreEqual(TestAllTypes.Types.NestedMessage.BbFieldNumber, 1);
Assert.AreEqual(TestAllTypes.OptionalInt32FieldNumber, 1);
Assert.AreEqual(TestAllTypes.OptionalGroupFieldNumber, 16);
Assert.AreEqual(TestAllTypes.OptionalNestedMessageFieldNumber, 18);
Assert.AreEqual(TestAllTypes.OptionalNestedEnumFieldNumber, 21);
Assert.AreEqual(TestAllTypes.RepeatedInt32FieldNumber, 31);
Assert.AreEqual(TestAllTypes.RepeatedGroupFieldNumber, 46);
Assert.AreEqual(TestAllTypes.RepeatedNestedMessageFieldNumber, 48);
Assert.AreEqual(TestAllTypes.RepeatedNestedEnumFieldNumber, 51);
}
[Test]
public void ExtensionConstantValues()
{
Assert.AreEqual(TestRequired.SingleFieldNumber, 1000);
Assert.AreEqual(TestRequired.MultiFieldNumber, 1001);
Assert.AreEqual(Unittest.OptionalInt32ExtensionFieldNumber, 1);
Assert.AreEqual(Unittest.OptionalGroupExtensionFieldNumber, 16);
Assert.AreEqual(Unittest.OptionalNestedMessageExtensionFieldNumber, 18);
Assert.AreEqual(Unittest.OptionalNestedEnumExtensionFieldNumber, 21);
Assert.AreEqual(Unittest.RepeatedInt32ExtensionFieldNumber, 31);
Assert.AreEqual(Unittest.RepeatedGroupExtensionFieldNumber, 46);
Assert.AreEqual(Unittest.RepeatedNestedMessageExtensionFieldNumber, 48);
Assert.AreEqual(Unittest.RepeatedNestedEnumExtensionFieldNumber, 51);
}
[Test]
public void EmptyPackedValue()
{
TestPackedTypes empty = new TestPackedTypes.Builder().Build();
Assert.AreEqual(0, empty.SerializedSize);
}
// oneof tests
[Test]
public void TestOneofEnumCase()
{
TestOneof2 message = TestOneof2.CreateBuilder()
.SetFooInt(123).SetFooString("foo").SetFooCord("bar").Build();
TestUtil.AssertAtMostOneFieldSetOneof(message);
}
[Test]
public void TestClearOneof()
{
TestOneof2.Builder builder = TestOneof2.CreateBuilder().SetFooInt(123);
Assert.AreEqual(TestOneof2.FooOneofCase.FooInt, builder.FooCase);
builder.ClearFoo();
Assert.AreEqual(TestOneof2.FooOneofCase.None, builder.FooCase);
}
[Test]
public void TestSetOneofClearsOthers()
{
TestOneof2.Builder builder = TestOneof2.CreateBuilder();
TestOneof2 message =
builder.SetFooInt(123).SetFooString("foo").Build();
Assert.IsTrue(message.HasFooString);
TestUtil.AssertAtMostOneFieldSetOneof(message);
message = builder.SetFooCord("bar").Build();
Assert.IsTrue(message.HasFooCord);
TestUtil.AssertAtMostOneFieldSetOneof(message);
message = builder.SetFooStringPiece("baz").Build();
Assert.IsTrue(message.HasFooStringPiece);
TestUtil.AssertAtMostOneFieldSetOneof(message);
message = builder.SetFooBytes(TestUtil.ToBytes("qux")).Build();
Assert.IsTrue(message.HasFooBytes);
TestUtil.AssertAtMostOneFieldSetOneof(message);
message = builder.SetFooEnum(TestOneof2.Types.NestedEnum.FOO).Build();
Assert.IsTrue(message.HasFooEnum);
TestUtil.AssertAtMostOneFieldSetOneof(message);
message = builder.SetFooMessage(
TestOneof2.Types.NestedMessage.CreateBuilder().SetQuxInt(234).Build()).Build();
Assert.IsTrue(message.HasFooMessage);
TestUtil.AssertAtMostOneFieldSetOneof(message);
message = builder.SetFooInt(123).Build();
Assert.IsTrue(message.HasFooInt);
TestUtil.AssertAtMostOneFieldSetOneof(message);
}
[Test]
public void TestOneofTypes_Primitive()
{
TestOneof2.Builder builder = TestOneof2.CreateBuilder();
Assert.AreEqual(builder.FooInt, 0);
Assert.IsFalse(builder.HasFooInt);
Assert.IsTrue(builder.SetFooInt(123).HasFooInt);
Assert.AreEqual(builder.FooInt, 123);
TestOneof2 message = builder.BuildPartial();
Assert.IsTrue(message.HasFooInt);
Assert.AreEqual(message.FooInt, 123);
Assert.IsFalse(builder.ClearFooInt().HasFooInt);
TestOneof2 message2 = builder.Build();
Assert.IsFalse(message2.HasFooInt);
Assert.AreEqual(message2.FooInt, 0);
}
[Test]
public void TestOneofTypes_Enum()
{
TestOneof2.Builder builder = TestOneof2.CreateBuilder();
Assert.AreEqual(builder.FooEnum, TestOneof2.Types.NestedEnum.FOO);
Assert.IsTrue(builder.SetFooEnum(TestOneof2.Types.NestedEnum.BAR).HasFooEnum);
Assert.AreEqual(builder.FooEnum, TestOneof2.Types.NestedEnum.BAR);
TestOneof2 message = builder.BuildPartial();
Assert.IsTrue(message.HasFooEnum);
Assert.AreEqual(message.FooEnum, TestOneof2.Types.NestedEnum.BAR);
Assert.IsFalse(builder.ClearFooEnum().HasFooEnum);
TestOneof2 message2 = builder.Build();
Assert.IsFalse(message2.HasFooEnum);
Assert.AreEqual(message2.FooEnum, TestOneof2.Types.NestedEnum.FOO);
}
[Test]
public void TestOneofTypes_String()
{
TestOneof2.Builder builder = TestOneof2.CreateBuilder();
Assert.AreEqual(builder.FooString, "");
Assert.IsTrue(builder.SetFooString("foo").HasFooString);
Assert.AreEqual(builder.FooString, "foo");
TestOneof2 message = builder.BuildPartial();
Assert.IsTrue(message.HasFooString);
Assert.AreEqual(message.FooString, "foo");
Assert.IsFalse(builder.ClearFooString().HasFooString);
TestOneof2 message2 = builder.Build();
Assert.IsFalse(message2.HasFooString);
Assert.AreEqual(message2.FooString, "");
builder.SetFooInt(123);
Assert.AreEqual(builder.FooString, "");
Assert.AreEqual(builder.FooInt, 123);
message = builder.Build();
Assert.AreEqual(message.FooString, "");
Assert.AreEqual(message.FooInt, 123);
}
[Test]
public void TestOneofTypes_Message()
{
TestOneof2.Builder builder = TestOneof2.CreateBuilder();
Assert.AreEqual(builder.FooMessage.QuxInt, 0);
builder.SetFooMessage(TestOneof2.Types.NestedMessage.CreateBuilder().SetQuxInt(234).Build());
Assert.IsTrue(builder.HasFooMessage);
Assert.AreEqual(builder.FooMessage.QuxInt, 234);
TestOneof2 message = builder.BuildPartial();
Assert.IsTrue(message.HasFooMessage);
Assert.AreEqual(message.FooMessage.QuxInt, 234);
Assert.IsFalse(builder.ClearFooMessage().HasFooMessage);
message = builder.Build();
Assert.IsFalse(message.HasFooMessage);
Assert.AreEqual(message.FooMessage.QuxInt, 0);
builder = TestOneof2.CreateBuilder();
Assert.IsFalse(builder.HasFooMessage);
builder.SetFooMessage(TestOneof2.Types.NestedMessage.CreateBuilder().SetQuxInt(123));
Assert.IsTrue(builder.HasFooMessage);
Assert.AreEqual(builder.FooMessage.QuxInt, 123);
message = builder.Build();
Assert.IsTrue(message.HasFooMessage);
Assert.AreEqual(message.FooMessage.QuxInt, 123);
}
[Test]
public void TestOneofMerge_Primitive()
{
TestOneof2.Builder builder = TestOneof2.CreateBuilder();
TestOneof2 message = builder.SetFooInt(123).Build();
TestOneof2 message2 = TestOneof2.CreateBuilder().MergeFrom(message).Build();
Assert.IsTrue(message2.HasFooInt);
Assert.AreEqual(message2.FooInt, 123);
}
[Test]
public void TestOneofMerge_String()
{
TestOneof2.Builder builder = TestOneof2.CreateBuilder();
TestOneof2 message = builder.SetFooString("foo").Build();
TestOneof2 message2 = TestOneof2.CreateBuilder().MergeFrom(message).Build();
Assert.IsTrue(message2.HasFooString);
Assert.AreEqual(message2.FooString, "foo");
}
[Test]
public void TestOneofMerge_Enum()
{
TestOneof2.Builder builder = TestOneof2.CreateBuilder();
TestOneof2 message = builder.SetFooEnum(TestOneof2.Types.NestedEnum.BAR).Build();
TestOneof2 message2 = TestOneof2.CreateBuilder().MergeFrom(message).Build();
Assert.IsTrue(message2.HasFooEnum);
Assert.AreEqual(message2.FooEnum, TestOneof2.Types.NestedEnum.BAR);
}
public void TestOneofMerge_message()
{
TestOneof2.Builder builder = TestOneof2.CreateBuilder();
TestOneof2 message = builder.SetFooMessage(
TestOneof2.Types.NestedMessage.CreateBuilder().SetQuxInt(234).Build()).Build();
TestOneof2 message2 = TestOneof2.CreateBuilder().MergeFrom(message).Build();
Assert.IsTrue(message2.HasFooMessage);
Assert.AreEqual(message2.FooMessage.QuxInt, 234);
}
[Test]
public void TestOneofMergeMixed()
{
TestOneof2.Builder builder = TestOneof2.CreateBuilder();
TestOneof2 message = builder.SetFooEnum(TestOneof2.Types.NestedEnum.BAR).Build();
TestOneof2 message2 =
TestOneof2.CreateBuilder().SetFooString("foo").MergeFrom(message).Build();
Assert.IsFalse(message2.HasFooString);
Assert.IsTrue(message2.HasFooEnum);
Assert.AreEqual(message2.FooEnum, TestOneof2.Types.NestedEnum.BAR);
}
[Test]
public void TestOneofSerialization_Primitive()
{
TestOneof2.Builder builder = TestOneof2.CreateBuilder();
TestOneof2 message = builder.SetFooInt(123).Build();
ByteString serialized = message.ToByteString();
TestOneof2 message2 = TestOneof2.ParseFrom(serialized);
Assert.IsTrue(message2.HasFooInt);
Assert.AreEqual(message2.FooInt, 123);
}
[Test]
public void TestOneofSerialization_String()
{
TestOneof2.Builder builder = TestOneof2.CreateBuilder();
TestOneof2 message = builder.SetFooString("foo").Build();
ByteString serialized = message.ToByteString();
TestOneof2 message2 = TestOneof2.ParseFrom(serialized);
Assert.IsTrue(message2.HasFooString);
Assert.AreEqual(message2.FooString, "foo");
}
[Test]
public void TestOneofSerialization_Enum()
{
TestOneof2.Builder builder = TestOneof2.CreateBuilder();
TestOneof2 message = builder.SetFooEnum(TestOneof2.Types.NestedEnum.BAR).Build();
ByteString serialized = message.ToByteString();
TestOneof2 message2 = TestOneof2.ParseFrom(serialized);
Assert.IsTrue(message2.HasFooEnum);
Assert.AreEqual(message2.FooEnum, TestOneof2.Types.NestedEnum.BAR);
}
[Test]
public void TestOneofSerialization_Message()
{
TestOneof2.Builder builder = TestOneof2.CreateBuilder();
TestOneof2 message = builder.SetFooMessage(
TestOneof2.Types.NestedMessage.CreateBuilder().SetQuxInt(234).Build()).Build();
ByteString serialized = message.ToByteString();
TestOneof2 message2 = TestOneof2.ParseFrom(serialized);
Assert.IsTrue(message2.HasFooMessage);
Assert.AreEqual(message2.FooMessage.QuxInt, 234);
public void DefaultValues()
{
// Single fields
var message = new TestAllTypes();
Assert.AreEqual(false, message.SingleBool);
Assert.AreEqual(ByteString.Empty, message.SingleBytes);
Assert.AreEqual(0.0, message.SingleDouble);
Assert.AreEqual(0, message.SingleFixed32);
Assert.AreEqual(0L, message.SingleFixed64);
Assert.AreEqual(0.0f, message.SingleFloat);
Assert.AreEqual(ForeignEnum.FOREIGN_UNSPECIFIED, message.SingleForeignEnum);
Assert.IsNull(message.SingleForeignMessage);
Assert.AreEqual(ImportEnum.IMPORT_ENUM_UNSPECIFIED, message.SingleImportEnum);
Assert.IsNull(message.SingleImportMessage);
Assert.AreEqual(0, message.SingleInt32);
Assert.AreEqual(0L, message.SingleInt64);
Assert.AreEqual(TestAllTypes.Types.NestedEnum.NESTED_ENUM_UNSPECIFIED, message.SingleNestedEnum);
Assert.IsNull(message.SingleNestedMessage);
Assert.IsNull(message.SinglePublicImportMessage);
Assert.AreEqual(0, message.SingleSfixed32);
Assert.AreEqual(0L, message.SingleSfixed64);
Assert.AreEqual(0, message.SingleSint32);
Assert.AreEqual(0L, message.SingleSint64);
Assert.AreEqual("", message.SingleString);
Assert.AreEqual(0U, message.SingleUint32);
Assert.AreEqual(0UL, message.SingleUint64);
// Repeated fields
Assert.AreEqual(0, message.RepeatedBool.Count);
Assert.AreEqual(0, message.RepeatedBytes.Count);
Assert.AreEqual(0, message.RepeatedDouble.Count);
Assert.AreEqual(0, message.RepeatedFixed32.Count);
Assert.AreEqual(0, message.RepeatedFixed64.Count);
Assert.AreEqual(0, message.RepeatedFloat.Count);
Assert.AreEqual(0, message.RepeatedForeignEnum.Count);
Assert.AreEqual(0, message.RepeatedForeignMessage.Count);
Assert.AreEqual(0, message.RepeatedImportEnum.Count);
Assert.AreEqual(0, message.RepeatedImportMessage.Count);
Assert.AreEqual(0, message.RepeatedNestedEnum.Count);
Assert.AreEqual(0, message.RepeatedNestedMessage.Count);
Assert.AreEqual(0, message.RepeatedPublicImportMessage.Count);
Assert.AreEqual(0, message.RepeatedSfixed32.Count);
Assert.AreEqual(0, message.RepeatedSfixed64.Count);
Assert.AreEqual(0, message.RepeatedSint32.Count);
Assert.AreEqual(0, message.RepeatedSint64.Count);
Assert.AreEqual(0, message.RepeatedString.Count);
Assert.AreEqual(0, message.RepeatedUint32.Count);
Assert.AreEqual(0, message.RepeatedUint64.Count);
// Oneof fields
Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.None, message.OneofFieldCase);
Assert.AreEqual(0, message.OneofUint32);
Assert.AreEqual("", message.OneofString);
Assert.AreEqual(ByteString.Empty, message.OneofBytes);
Assert.IsNull(message.OneofNestedMessage);
}
[Test]
public void RoundTrip_Empty()
{
var message = new TestAllTypes();
// Without setting any values, there's nothing to write.
byte[] bytes = message.ToByteArray();
Assert.AreEqual(0, bytes.Length);
TestAllTypes parsed = TestAllTypes.Parser.ParseFrom(bytes);
Assert.AreEqual(message, parsed);
}
[Test]
public void RoundTrip_SingleValues()
{
var message = new TestAllTypes
{
SingleBool = true,
SingleBytes = ByteString.CopyFrom(new byte[] { 1, 2, 3, 4 }),
SingleDouble = 23.5,
SingleFixed32 = 23,
SingleFixed64 = 1234567890123,
SingleFloat = 12.25f,
SingleForeignEnum = ForeignEnum.FOREIGN_BAR,
SingleForeignMessage = new ForeignMessage { C = 10 },
SingleImportEnum = ImportEnum.IMPORT_BAZ,
SingleImportMessage = new ImportMessage { D = 20 },
SingleInt32 = 100,
SingleInt64 = 3210987654321,
SingleNestedEnum = TestAllTypes.Types.NestedEnum.FOO,
SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 35 },
SinglePublicImportMessage = new PublicImportMessage { E = 54 },
SingleSfixed32 = -123,
SingleSfixed64 = -12345678901234,
SingleSint32 = -456,
SingleSint64 = -12345678901235,
SingleString = "test",
SingleUint32 = uint.MaxValue,
SingleUint64 = ulong.MaxValue
};
byte[] bytes = message.ToByteArray();
TestAllTypes parsed = TestAllTypes.Parser.ParseFrom(bytes);
Assert.AreEqual(message, parsed);
}
[Test]
public void RoundTrip_RepeatedValues()
{
var message = new TestAllTypes
{
RepeatedBool = { true, false },
RepeatedBytes = { ByteString.CopyFrom(new byte[] { 1, 2, 3, 4 }), ByteString.CopyFrom(new byte[] { 5, 6 }) },
RepeatedDouble = { -12.25, 23.5 },
RepeatedFixed32 = { uint.MaxValue, 23 },
RepeatedFixed64 = { ulong.MaxValue, 1234567890123 },
RepeatedFloat = { 100f, 12.25f },
RepeatedForeignEnum = { ForeignEnum.FOREIGN_FOO, ForeignEnum.FOREIGN_BAR },
RepeatedForeignMessage = { new ForeignMessage(), new ForeignMessage { C = 10 } },
RepeatedImportEnum = { ImportEnum.IMPORT_BAZ, ImportEnum.IMPORT_ENUM_UNSPECIFIED },
RepeatedImportMessage = { new ImportMessage { D = 20 }, new ImportMessage { D = 25 } },
RepeatedInt32 = { 100, 200 },
RepeatedInt64 = { 3210987654321, long.MaxValue },
RepeatedNestedEnum = { TestAllTypes.Types.NestedEnum.FOO, TestAllTypes.Types.NestedEnum.NEG },
RepeatedNestedMessage = { new TestAllTypes.Types.NestedMessage { Bb = 35 }, new TestAllTypes.Types.NestedMessage { Bb = 10 } },
RepeatedPublicImportMessage = { new PublicImportMessage { E = 54 }, new PublicImportMessage { E = -1 } },
RepeatedSfixed32 = { -123, 123 },
RepeatedSfixed64 = { -12345678901234, 12345678901234 },
RepeatedSint32 = { -456, 100 },
RepeatedSint64 = { -12345678901235, 123 },
RepeatedString = { "foo", "bar" },
RepeatedUint32 = { uint.MaxValue, uint.MinValue },
RepeatedUint64 = { ulong.MaxValue, uint.MinValue }
};
byte[] bytes = message.ToByteArray();
TestAllTypes parsed = TestAllTypes.Parser.ParseFrom(bytes);
Assert.AreEqual(message, parsed);
}
}
}
}

@ -34,13 +34,12 @@
#endregion
using Google.ProtocolBuffers.Descriptors;
using Google.Protobuf.Descriptors;
using UnitTest.Issues.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers
namespace Google.Protobuf
{
/// <summary>
/// Tests for issues which aren't easily compartmentalized into other unit tests.
@ -51,10 +50,11 @@ namespace Google.ProtocolBuffers
[Test]
public void FieldCalledItem()
{
ItemField message = new ItemField.Builder { Item = 3 }.Build();
ItemField message = new ItemField { Item = 3 };
FieldDescriptor field = ItemField.Descriptor.FindFieldByName("item");
Assert.NotNull(field);
Assert.AreEqual(3, (int)message[field]);
// TODO(jonskeet): Reflection...
// Assert.AreEqual(3, (int)message[field]);
}
}
}

@ -1,90 +0,0 @@
#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.Collections.Generic;
using System.IO;
using Google.ProtocolBuffers.TestProtos;
using NUnit.Framework;
using NestedMessage = Google.ProtocolBuffers.TestProtos.TestAllTypes.Types.NestedMessage;
namespace Google.ProtocolBuffers
{
public class MessageStreamIteratorTest
{
[Test]
public void ThreeMessagesInMemory()
{
MemoryStream stream = new MemoryStream(MessageStreamWriterTest.ThreeMessageData);
IEnumerable<NestedMessage> iterator = MessageStreamIterator<NestedMessage>.FromStreamProvider(() => stream);
List<NestedMessage> messages = new List<NestedMessage>(iterator);
Assert.AreEqual(3, messages.Count);
Assert.AreEqual(5, messages[0].Bb);
Assert.AreEqual(1500, messages[1].Bb);
Assert.IsFalse(messages[2].HasBb);
}
[Test]
public void ManyMessagesShouldNotTriggerSizeAlert()
{
int messageSize = TestUtil.GetAllSet().SerializedSize;
// Enough messages to trigger the alert unless we've reset the size
// Note that currently we need to make this big enough to copy two whole buffers,
// as otherwise when we refill the buffer the second type, the alert triggers instantly.
int correctCount = (CodedInputStream.BufferSize*2)/messageSize + 1;
using (MemoryStream stream = new MemoryStream())
{
MessageStreamWriter<TestAllTypes> writer = new MessageStreamWriter<TestAllTypes>(stream);
for (int i = 0; i < correctCount; i++)
{
writer.Write(TestUtil.GetAllSet());
}
writer.Flush();
stream.Position = 0;
int count = 0;
foreach (var message in MessageStreamIterator<TestAllTypes>.FromStreamProvider(() => stream)
.WithSizeLimit(CodedInputStream.BufferSize*2))
{
count++;
TestUtil.AssertAllFieldsSet(message);
}
Assert.AreEqual(correctCount, count);
}
}
}
}

@ -1,78 +0,0 @@
#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.IO;
using NUnit.Framework;
using NestedMessage = Google.ProtocolBuffers.TestProtos.TestAllTypes.Types.NestedMessage;
namespace Google.ProtocolBuffers
{
public class MessageStreamWriterTest
{
internal static readonly byte[] ThreeMessageData = new byte[]
{
(1 << 3) | 2, 2,
// Field 1, 2 bytes long (first message)
(1 << 3) | 0, 5, // Field 1, value 5
(1 << 3) | 2, 3,
// Field 1, 3 bytes long (second message)
(1 << 3) | 0, (1500 & 0x7f) | 0x80, 1500 >> 7,
// Field 1, value 1500
(1 << 3) | 2, 0, // Field 1, no data (third message)
};
[Test]
public void ThreeMessages()
{
NestedMessage message1 = new NestedMessage.Builder {Bb = 5}.Build();
NestedMessage message2 = new NestedMessage.Builder {Bb = 1500}.Build();
NestedMessage message3 = new NestedMessage.Builder().Build();
byte[] data;
using (MemoryStream stream = new MemoryStream())
{
MessageStreamWriter<NestedMessage> writer = new MessageStreamWriter<NestedMessage>(stream);
writer.Write(message1);
writer.Write(message2);
writer.Write(message3);
writer.Flush();
data = stream.ToArray();
}
TestUtil.AssertEqualBytes(ThreeMessageData, data);
}
}
}

@ -1,344 +0,0 @@
#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.IO;
using Google.ProtocolBuffers.Descriptors;
using Google.ProtocolBuffers.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers
{
/// <summary>
/// Miscellaneous tests for message operations that apply to both
/// generated and dynamic messages.
/// </summary>
public class MessageTest
{
// =================================================================
// Message-merging tests.
private static readonly TestAllTypes MergeSource = new TestAllTypes.Builder
{
OptionalInt32 = 1,
OptionalString = "foo",
OptionalForeignMessage =
ForeignMessage.DefaultInstance,
}.AddRepeatedString("bar").Build();
private static readonly TestAllTypes MergeDest = new TestAllTypes.Builder
{
OptionalInt64 = 2,
OptionalString = "baz",
OptionalForeignMessage =
new ForeignMessage.Builder {C = 3}.Build(),
}.AddRepeatedString("qux").Build();
private const string MergeResultText =
"optional_int32: 1\n" +
"optional_int64: 2\n" +
"optional_string: \"foo\"\n" +
"optional_foreign_message {\n" +
" c: 3\n" +
"}\n" +
"repeated_string: \"qux\"\n" +
"repeated_string: \"bar\"\n";
[Test]
public void MergeFrom()
{
TestAllTypes result = TestAllTypes.CreateBuilder(MergeDest).MergeFrom(MergeSource).Build();
Assert.AreEqual(MergeResultText, result.ToString());
}
/// <summary>
/// Test merging a DynamicMessage into a GeneratedMessage.
/// As long as they have the same descriptor, this should work, but it is an
/// entirely different code path.
/// </summary>
[Test]
public void MergeFromDynamic()
{
TestAllTypes result = (TestAllTypes) TestAllTypes.CreateBuilder(MergeDest)
.MergeFrom(DynamicMessage.CreateBuilder(MergeSource).Build())
.Build();
Assert.AreEqual(MergeResultText, result.ToString());
}
/// <summary>
/// Test merging two DynamicMessages.
/// </summary>
[Test]
public void DynamicMergeFrom()
{
DynamicMessage result = (DynamicMessage) DynamicMessage.CreateBuilder(MergeDest)
.MergeFrom(
(DynamicMessage)
DynamicMessage.CreateBuilder(MergeSource).Build())
.Build();
Assert.AreEqual(MergeResultText, result.ToString());
}
// =================================================================
// Required-field-related tests.
private static readonly TestRequired TestRequiredUninitialized = TestRequired.DefaultInstance;
private static readonly TestRequired TestRequiredInitialized = new TestRequired.Builder
{
A = 1,
B = 2,
C = 3
}.Build();
[Test]
public void Initialization()
{
TestRequired.Builder builder = TestRequired.CreateBuilder();
Assert.IsFalse(builder.IsInitialized);
builder.A = 1;
Assert.IsFalse(builder.IsInitialized);
builder.B = 1;
Assert.IsFalse(builder.IsInitialized);
builder.C = 1;
Assert.IsTrue(builder.IsInitialized);
}
[Test]
public void UninitializedBuilderToString()
{
TestRequired.Builder builder = TestRequired.CreateBuilder().SetA(1);
Assert.AreEqual("a: 1\n", builder.ToString());
}
[Test]
public void RequiredForeign()
{
TestRequiredForeign.Builder builder = TestRequiredForeign.CreateBuilder();
Assert.IsTrue(builder.IsInitialized);
builder.SetOptionalMessage(TestRequiredUninitialized);
Assert.IsFalse(builder.IsInitialized);
builder.SetOptionalMessage(TestRequiredInitialized);
Assert.IsTrue(builder.IsInitialized);
builder.AddRepeatedMessage(TestRequiredUninitialized);
Assert.IsFalse(builder.IsInitialized);
builder.SetRepeatedMessage(0, TestRequiredInitialized);
Assert.IsTrue(builder.IsInitialized);
}
[Test]
public void RequiredExtension()
{
TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder();
Assert.IsTrue(builder.IsInitialized);
builder.SetExtension(TestRequired.Single, TestRequiredUninitialized);
Assert.IsFalse(builder.IsInitialized);
builder.SetExtension(TestRequired.Single, TestRequiredInitialized);
Assert.IsTrue(builder.IsInitialized);
builder.AddExtension(TestRequired.Multi, TestRequiredUninitialized);
Assert.IsFalse(builder.IsInitialized);
builder.SetExtension(TestRequired.Multi, 0, TestRequiredInitialized);
Assert.IsTrue(builder.IsInitialized);
}
[Test]
public void RequiredDynamic()
{
MessageDescriptor descriptor = TestRequired.Descriptor;
DynamicMessage.Builder builder = DynamicMessage.CreateBuilder(descriptor);
Assert.IsFalse(builder.IsInitialized);
builder[descriptor.FindDescriptor<FieldDescriptor>("a")] = 1;
Assert.IsFalse(builder.IsInitialized);
builder[descriptor.FindDescriptor<FieldDescriptor>("b")] = 1;
Assert.IsFalse(builder.IsInitialized);
builder[descriptor.FindDescriptor<FieldDescriptor>("c")] = 1;
Assert.IsTrue(builder.IsInitialized);
}
[Test]
public void RequiredDynamicForeign()
{
MessageDescriptor descriptor = TestRequiredForeign.Descriptor;
DynamicMessage.Builder builder = DynamicMessage.CreateBuilder(descriptor);
Assert.IsTrue(builder.IsInitialized);
builder[descriptor.FindDescriptor<FieldDescriptor>("optional_message")] = TestRequiredUninitialized;
Assert.IsFalse(builder.IsInitialized);
builder[descriptor.FindDescriptor<FieldDescriptor>("optional_message")] = TestRequiredInitialized;
Assert.IsTrue(builder.IsInitialized);
builder.AddRepeatedField(descriptor.FindDescriptor<FieldDescriptor>("repeated_message"),
TestRequiredUninitialized);
Assert.IsFalse(builder.IsInitialized);
builder.SetRepeatedField(descriptor.FindDescriptor<FieldDescriptor>("repeated_message"), 0,
TestRequiredInitialized);
Assert.IsTrue(builder.IsInitialized);
}
[Test]
public void UninitializedException()
{
var e = Assert.Throws<UninitializedMessageException>(() => TestRequired.CreateBuilder().Build());
Assert.AreEqual("Message missing required fields: a, b, c", e.Message);
}
[Test]
public void BuildPartial()
{
// We're mostly testing that no exception is thrown.
TestRequired message = TestRequired.CreateBuilder().BuildPartial();
Assert.IsFalse(message.IsInitialized);
}
[Test]
public void NestedUninitializedException()
{
var e = Assert.Throws<UninitializedMessageException>(() => TestRequiredForeign.CreateBuilder()
.SetOptionalMessage(TestRequiredUninitialized)
.AddRepeatedMessage(TestRequiredUninitialized)
.AddRepeatedMessage(TestRequiredUninitialized)
.Build());
Assert.AreEqual(
"Message missing required fields: " +
"optional_message.a, " +
"optional_message.b, " +
"optional_message.c, " +
"repeated_message[0].a, " +
"repeated_message[0].b, " +
"repeated_message[0].c, " +
"repeated_message[1].a, " +
"repeated_message[1].b, " +
"repeated_message[1].c",
e.Message);
}
[Test]
public void BuildNestedPartial()
{
// We're mostly testing that no exception is thrown.
TestRequiredForeign message =
TestRequiredForeign.CreateBuilder()
.SetOptionalMessage(TestRequiredUninitialized)
.AddRepeatedMessage(TestRequiredUninitialized)
.AddRepeatedMessage(TestRequiredUninitialized)
.BuildPartial();
Assert.IsFalse(message.IsInitialized);
}
[Test]
public void ParseUninitialized()
{
var e = Assert.Throws<InvalidProtocolBufferException>(() => TestRequired.ParseFrom(ByteString.Empty));
Assert.AreEqual("Message missing required fields: a, b, c", e.Message);
}
[Test]
public void ParseNestedUnititialized()
{
ByteString data =
TestRequiredForeign.CreateBuilder()
.SetOptionalMessage(TestRequiredUninitialized)
.AddRepeatedMessage(TestRequiredUninitialized)
.AddRepeatedMessage(TestRequiredUninitialized)
.BuildPartial().ToByteString();
var e = Assert.Throws<InvalidProtocolBufferException>(() => TestRequiredForeign.ParseFrom(data));
Assert.AreEqual(
"Message missing required fields: " +
"optional_message.a, " +
"optional_message.b, " +
"optional_message.c, " +
"repeated_message[0].a, " +
"repeated_message[0].b, " +
"repeated_message[0].c, " +
"repeated_message[1].a, " +
"repeated_message[1].b, " +
"repeated_message[1].c",
e.Message);
}
[Test]
public void DynamicUninitializedException()
{
var e = Assert.Throws<UninitializedMessageException>(() => DynamicMessage.CreateBuilder(TestRequired.Descriptor).Build());
Assert.AreEqual("Message missing required fields: a, b, c", e.Message);
}
[Test]
public void DynamicBuildPartial()
{
// We're mostly testing that no exception is thrown.
DynamicMessage message = DynamicMessage.CreateBuilder(TestRequired.Descriptor).BuildPartial();
Assert.IsFalse(message.Initialized);
}
[Test]
public void DynamicParseUnititialized()
{
MessageDescriptor descriptor = TestRequired.Descriptor;
var e = Assert.Throws<InvalidProtocolBufferException>(() => DynamicMessage.ParseFrom(descriptor, ByteString.Empty));
Assert.AreEqual("Message missing required fields: a, b, c", e.Message);
}
[Test]
public void PackedTypesWrittenDirectlyToStream()
{
TestPackedTypes message = new TestPackedTypes.Builder {PackedInt32List = {0, 1, 2}}.Build();
MemoryStream stream = new MemoryStream();
message.WriteTo(stream);
stream.Position = 0;
TestPackedTypes readMessage = TestPackedTypes.ParseFrom(stream);
Assert.AreEqual(message, readMessage);
}
}
}

@ -1,82 +0,0 @@
#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 Google.ProtocolBuffers.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers
{
public class MessageUtilTest
{
[Test]
public void NullTypeName()
{
Assert.Throws<ArgumentNullException>(() => MessageUtil.GetDefaultMessage((string) null));
}
[Test]
public void InvalidTypeName()
{
Assert.Throws<ArgumentException>(() => MessageUtil.GetDefaultMessage("invalidtypename"));
}
[Test]
public void ValidTypeName()
{
Assert.AreSame(TestAllTypes.DefaultInstance,
MessageUtil.GetDefaultMessage(typeof(TestAllTypes).AssemblyQualifiedName));
}
[Test]
public void NullType()
{
Assert.Throws<ArgumentNullException>(() => MessageUtil.GetDefaultMessage((Type)null));
}
[Test]
public void NonMessageType()
{
Assert.Throws<ArgumentException>(() => MessageUtil.GetDefaultMessage(typeof(string)));
}
[Test]
public void ValidType()
{
Assert.AreSame(TestAllTypes.DefaultInstance, MessageUtil.GetDefaultMessage(typeof(TestAllTypes)));
}
}
}

@ -1,81 +0,0 @@
#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 NUnit.Framework;
namespace Google.ProtocolBuffers
{
public class NameHelpersTest
{
[Test]
public void UnderscoresToPascalCase()
{
Assert.AreEqual("FooBar", NameHelpers.UnderscoresToPascalCase("Foo_bar"));
Assert.AreEqual("FooBar", NameHelpers.UnderscoresToPascalCase("foo_bar"));
Assert.AreEqual("Foo0Bar", NameHelpers.UnderscoresToPascalCase("Foo0bar"));
Assert.AreEqual("FooBar", NameHelpers.UnderscoresToPascalCase("Foo_+_Bar"));
Assert.AreEqual("Bar", NameHelpers.UnderscoresToPascalCase("__+bar"));
Assert.AreEqual("Bar", NameHelpers.UnderscoresToPascalCase("bar_"));
Assert.AreEqual("_0Bar", NameHelpers.UnderscoresToPascalCase("_0bar"));
Assert.AreEqual("_1Bar", NameHelpers.UnderscoresToPascalCase("_1_bar"));
}
[Test]
public void UnderscoresToCamelCase()
{
Assert.AreEqual("fooBar", NameHelpers.UnderscoresToCamelCase("Foo_bar"));
Assert.AreEqual("fooBar", NameHelpers.UnderscoresToCamelCase("foo_bar"));
Assert.AreEqual("foo0Bar", NameHelpers.UnderscoresToCamelCase("Foo0bar"));
Assert.AreEqual("fooBar", NameHelpers.UnderscoresToCamelCase("Foo_+_Bar"));
Assert.AreEqual("bar", NameHelpers.UnderscoresToCamelCase("__+bar"));
Assert.AreEqual("bar", NameHelpers.UnderscoresToCamelCase("bar_"));
Assert.AreEqual("_0Bar", NameHelpers.UnderscoresToCamelCase("_0bar"));
Assert.AreEqual("_1Bar", NameHelpers.UnderscoresToCamelCase("_1_bar"));
}
[Test]
public void StripSuffix()
{
string text = "FooBar";
Assert.IsFalse(NameHelpers.StripSuffix(ref text, "Foo"));
Assert.AreEqual("FooBar", text);
Assert.IsTrue(NameHelpers.StripSuffix(ref text, "Bar"));
Assert.AreEqual("Foo", text);
}
}
}

@ -8,8 +8,8 @@
<ProjectGuid>{DD01ED24-3750-4567-9A23-1DB676A15610}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Google.ProtocolBuffers</RootNamespace>
<AssemblyName>Google.ProtocolBuffers.Test</AssemblyName>
<RootNamespace>Google.Protobuf</RootNamespace>
<AssemblyName>Google.Protobuf.Test</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<SignAssembly>true</SignAssembly>
@ -71,79 +71,37 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="AbstractMessageTest.cs" />
<Compile Include="ByteStringTest.cs" />
<Compile Include="FieldPresenceTest.cs" />
<Compile Include="CodedInputStreamTest.cs" />
<Compile Include="CodedOutputStreamTest.cs" />
<Compile Include="Collections\PopsicleListTest.cs" />
<Compile Include="Compatibility\BinaryCompatibilityTests.cs" />
<Compile Include="Compatibility\CompatibilityTests.cs" />
<Compile Include="Compatibility\DictionaryCompatibilityTests.cs" />
<Compile Include="Compatibility\JsonCompatibilityTests.cs" />
<Compile Include="Compatibility\TestResources.cs" />
<Compile Include="Compatibility\TextCompatibilityTests.cs" />
<Compile Include="Compatibility\XmlCompatibilityTests.cs" />
<Compile Include="TestProtos\GoogleSize.cs" />
<Compile Include="TestProtos\GoogleSpeed.cs" />
<Compile Include="TestProtos\Unittest.cs" />
<Compile Include="TestProtos\UnittestCustomOptions.cs" />
<Compile Include="TestProtos\UnittestDropUnknownFields.cs" />
<Compile Include="TestProtos\UnittestEnormousDescriptor.cs" />
<Compile Include="TestProtos\UnittestExtrasXmltest.cs" />
<Compile Include="TestProtos\UnittestImport.cs" />
<Compile Include="TestProtos\UnittestImportPublic.cs" />
<Compile Include="GeneratedMessageTest.cs" />
<Compile Include="RepeatedFieldTest.cs" />
<Compile Include="TestProtos\UnittestImportProto3.cs" />
<Compile Include="TestProtos\UnittestImportPublicProto3.cs" />
<Compile Include="TestProtos\UnittestIssues.cs" />
<Compile Include="TestProtos\UnittestMset.cs" />
<Compile Include="TestProtos\UnittestNoFieldPresence.cs" />
<Compile Include="TestProtos\UnittestOptimizeFor.cs" />
<Compile Include="TestProtos\UnknownEnumTest.cs" />
<Compile Include="TestResources.cs" />
<Compile Include="TestReaderForUrlEncoded.cs" />
<Compile Include="TestProtos\UnittestProto3.cs" />
<Compile Include="DeprecatedMemberTest.cs" />
<Compile Include="DescriptorsTest.cs" />
<Compile Include="DynamicMessageTest.cs" />
<Compile Include="ExtendableMessageTest.cs" />
<Compile Include="GeneratedBuilderTest.cs" />
<Compile Include="GeneratedMessageTest.cs" />
<Compile Include="IssuesTest.cs" />
<Compile Include="MessageStreamIteratorTest.cs" />
<Compile Include="MessageStreamWriterTest.cs" />
<Compile Include="MessageTest.cs" />
<Compile Include="MessageUtilTest.cs" />
<Compile Include="NameHelpersTest.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="ReflectionTester.cs" />
<Compile Include="ReusableBuilderTest.cs" />
<Compile Include="TestCornerCases.cs" />
<Compile Include="TestMimeMessageFormats.cs" />
<Compile Include="TestUtil.cs" />
<Compile Include="TestWriterFormatJson.cs" />
<Compile Include="TestWriterFormatXml.cs" />
<Compile Include="TextFormatTest.cs" />
<Compile Include="UnknownFieldSetTest.cs" />
<Compile Include="WireFormatTest.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ProtocolBuffers.Serialization\ProtocolBuffers.Serialization.csproj">
<Project>{231391AF-449C-4a39-986C-AD7F270F4750}</Project>
<Name>ProtocolBuffers.Serialization</Name>
</ProjectReference>
<ProjectReference Include="..\ProtocolBuffers\ProtocolBuffers.csproj">
<Project>{6908BDCE-D925-43F3-94AC-A531E6DF2591}</Project>
<Name>ProtocolBuffers</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Compatibility\google_message1.dat" />
<EmbeddedResource Include="Compatibility\google_message2.dat" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
<ItemGroup>
<Folder Include="Collections\" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.

File diff suppressed because it is too large Load Diff

@ -0,0 +1,50 @@
using System;
using System.Collections.Generic;
using Google.Protobuf.Collections;
using NUnit.Framework;
namespace Google.Protobuf
{
public class RepeatedFieldTest
{
[Test]
public void NullValuesRejected()
{
var list = new RepeatedField<string>();
Assert.Throws<ArgumentNullException>(() => list.Add((string) null));
Assert.Throws<ArgumentNullException>(() => list.Add((IEnumerable<string>) null));
Assert.Throws<ArgumentNullException>(() => list.Add((RepeatedField<string>)null));
Assert.Throws<ArgumentNullException>(() => list.Contains(null));
Assert.Throws<ArgumentNullException>(() => list.IndexOf(null));
}
[Test]
public void Add_SingleItem()
{
var list = new RepeatedField<string>();
list.Add("foo");
Assert.AreEqual(1, list.Count);
Assert.AreEqual("foo", list[0]);
}
[Test]
public void Add_Sequence()
{
var list = new RepeatedField<string>();
list.Add(new[] { "foo", "bar" });
Assert.AreEqual(2, list.Count);
Assert.AreEqual("foo", list[0]);
Assert.AreEqual("bar", list[1]);
}
[Test]
public void Add_RepeatedField()
{
var list = new RepeatedField<string>();
list.Add(new RepeatedField<string> { "foo", "bar" });
Assert.AreEqual(2, list.Count);
Assert.AreEqual("foo", list[0]);
Assert.AreEqual("bar", list[1]);
}
}
}

@ -1,166 +0,0 @@
using System;
using Google.ProtocolBuffers.Collections;
using Google.ProtocolBuffers.TestProtos;
using UnitTest.Issues.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers
{
public class ReusableBuilderTest
{
//Issue 28: Circular message dependencies result in null defaults for DefaultInstance
[Test]
public void EnsureStaticCicularReference()
{
MyMessageAReferenceB ab = MyMessageAReferenceB.DefaultInstance;
Assert.NotNull(ab);
Assert.NotNull(ab.Value);
MyMessageBReferenceA ba = MyMessageBReferenceA.DefaultInstance;
Assert.NotNull(ba);
Assert.NotNull(ba.Value);
}
[Test]
public void TestModifyDefaultInstance()
{
//verify that the default instance has correctly been marked as read-only
Assert.AreEqual(typeof(PopsicleList<bool>), TestAllTypes.DefaultInstance.RepeatedBoolList.GetType());
PopsicleList<bool> list = (PopsicleList<bool>)TestAllTypes.DefaultInstance.RepeatedBoolList;
Assert.IsTrue(list.IsReadOnly);
}
[Test]
public void TestUnmodifiedDefaultInstance()
{
//Simply calling ToBuilder().Build() no longer creates a copy of the message
TestAllTypes.Builder builder = TestAllTypes.DefaultInstance.ToBuilder();
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
}
[Test]
public void BuildMultipleWithoutChange()
{
//Calling Build() or BuildPartial() does not require a copy of the message
TestAllTypes.Builder builder = TestAllTypes.DefaultInstance.ToBuilder();
builder.SetDefaultBool(true);
TestAllTypes first = builder.BuildPartial();
//Still the same instance?
Assert.IsTrue(ReferenceEquals(first, builder.Build()));
//Still the same instance?
Assert.IsTrue(ReferenceEquals(first, builder.BuildPartial().ToBuilder().Build()));
}
[Test]
public void MergeFromDefaultInstance()
{
TestAllTypes.Builder builder = TestAllTypes.DefaultInstance.ToBuilder();
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
builder.MergeFrom(TestAllTypes.DefaultInstance);
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
}
[Test]
public void BuildNewBuilderIsDefaultInstance()
{
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, new TestAllTypes.Builder().Build()));
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, TestAllTypes.CreateBuilder().Build()));
//last test, if you clear a builder it reverts to default instance
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance,
TestAllTypes.CreateBuilder().SetOptionalBool(true).Build().ToBuilder().Clear().Build()));
}
[Test]
public void BuildModifyAndRebuild()
{
TestAllTypes.Builder b1 = new TestAllTypes.Builder();
b1.SetDefaultInt32(1);
b1.AddRepeatedInt32(2);
b1.SetOptionalForeignMessage(ForeignMessage.DefaultInstance);
TestAllTypes m1 = b1.Build();
b1.SetDefaultInt32(5);
b1.AddRepeatedInt32(6);
b1.SetOptionalForeignMessage(b1.OptionalForeignMessage.ToBuilder().SetC(7));
TestAllTypes m2 = b1.Build();
Assert.AreEqual("{\"optional_foreign_message\":{},\"repeated_int32\":[2],\"default_int32\":1}", Extensions.ToJson(m1));
Assert.AreEqual("{\"optional_foreign_message\":{\"c\":7},\"repeated_int32\":[2,6],\"default_int32\":5}", Extensions.ToJson(m2));
}
[Test]
public void CloneOnChangePrimitive()
{
TestAllTypes.Builder builder = TestAllTypes.DefaultInstance.ToBuilder();
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
builder.SetDefaultBool(true);
Assert.IsFalse(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
}
[Test]
public void CloneOnAddRepeatedBool()
{
TestAllTypes.Builder builder = TestAllTypes.DefaultInstance.ToBuilder();
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
builder.AddRepeatedBool(true);
Assert.IsFalse(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
}
[Test]
public void CloneOnGetRepeatedBoolList()
{
TestAllTypes.Builder builder = TestAllTypes.DefaultInstance.ToBuilder();
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
GC.KeepAlive(builder.RepeatedBoolList);
Assert.IsFalse(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
}
[Test]
public void CloneOnChangeMessage()
{
TestAllTypes.Builder builder = TestAllTypes.DefaultInstance.ToBuilder();
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
builder.SetOptionalForeignMessage(new ForeignMessage.Builder());
Assert.IsFalse(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
}
[Test]
public void CloneOnClearMessage()
{
TestAllTypes.Builder builder = TestAllTypes.DefaultInstance.ToBuilder();
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
builder.ClearOptionalForeignMessage();
Assert.IsFalse(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
}
[Test]
public void CloneOnGetRepeatedForeignMessageList()
{
TestAllTypes.Builder builder = TestAllTypes.DefaultInstance.ToBuilder();
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
GC.KeepAlive(builder.RepeatedForeignMessageList);
Assert.IsFalse(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
}
[Test]
public void CloneOnChangeEnumValue()
{
TestAllTypes.Builder builder = TestAllTypes.DefaultInstance.ToBuilder();
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
builder.SetOptionalForeignEnum(ForeignEnum.FOREIGN_BAR);
Assert.IsFalse(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
}
[Test]
public void CloneOnGetRepeatedForeignEnumList()
{
TestAllTypes.Builder builder = TestAllTypes.DefaultInstance.ToBuilder();
Assert.IsTrue(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
GC.KeepAlive(builder.RepeatedForeignEnumList);
Assert.IsFalse(ReferenceEquals(TestAllTypes.DefaultInstance, builder.Build()));
}
}
}

@ -1,25 +1,21 @@
using UnitTest.Issues.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers
namespace Google.Protobuf
{
public class TestCornerCases
{
[Test]
public void TestRoundTripNegativeEnums()
{
NegativeEnumMessage msg = NegativeEnumMessage.CreateBuilder()
.SetValue(NegativeEnum.MinusOne) //11
.AddValues(NegativeEnum.Zero) //2
.AddValues(NegativeEnum.MinusOne) //11
.AddValues(NegativeEnum.FiveBelow) //11
//2
.AddPackedValues(NegativeEnum.Zero) //1
.AddPackedValues(NegativeEnum.MinusOne) //10
.AddPackedValues(NegativeEnum.FiveBelow) //10
.Build();
NegativeEnumMessage msg = new NegativeEnumMessage
{
Value = NegativeEnum.MinusOne,
Values = { NegativeEnum.NEGATIVE_ENUM_ZERO, NegativeEnum.MinusOne, NegativeEnum.FiveBelow },
PackedValues = { NegativeEnum.NEGATIVE_ENUM_ZERO, NegativeEnum.MinusOne, NegativeEnum.FiveBelow }
};
Assert.AreEqual(58, msg.SerializedSize);
Assert.AreEqual(58, msg.CalculateSize());
byte[] bytes = new byte[58];
CodedOutputStream output = CodedOutputStream.CreateInstance(bytes);
@ -27,7 +23,7 @@ namespace Google.ProtocolBuffers
msg.WriteTo(output);
Assert.AreEqual(0, output.SpaceLeft);
NegativeEnumMessage copy = NegativeEnumMessage.ParseFrom(bytes);
NegativeEnumMessage copy = NegativeEnumMessage.Parser.ParseFrom(bytes);
Assert.AreEqual(msg, copy);
}
}

@ -1,277 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Google.ProtocolBuffers.Serialization;
using Google.ProtocolBuffers.Serialization.Http;
using Google.ProtocolBuffers.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers
{
public class TestMimeMessageFormats
{
// There is a whole host of various json mime types in use around the net, this is the set we accept...
readonly IEnumerable<string> JsonTypes = new string[] { "application/json", "application/x-json", "application/x-javascript", "text/javascript", "text/x-javascript", "text/x-json", "text/json" };
readonly IEnumerable<string> XmlTypes = new string[] { "text/xml", "application/xml" };
readonly IEnumerable<string> ProtobufTypes = new string[] { "application/binary", "application/x-protobuf", "application/vnd.google.protobuf" };
[Test]
public void TestReadJsonMimeTypes()
{
foreach (string type in JsonTypes)
{
Assert.IsTrue(
MessageFormatFactory.CreateInputStream(new MessageFormatOptions(), type, Stream.Null)
is JsonFormatReader);
}
Assert.IsTrue(
MessageFormatFactory.CreateInputStream(new MessageFormatOptions() { DefaultContentType = "application/json" }, null, Stream.Null)
is JsonFormatReader);
}
[Test]
public void TestWriteJsonMimeTypes()
{
foreach (string type in JsonTypes)
{
Assert.IsTrue(
MessageFormatFactory.CreateOutputStream(new MessageFormatOptions(), type, Stream.Null)
is JsonFormatWriter);
}
Assert.IsTrue(
MessageFormatFactory.CreateOutputStream(new MessageFormatOptions() { DefaultContentType = "application/json" }, null, Stream.Null)
is JsonFormatWriter);
}
[Test]
public void TestReadXmlMimeTypes()
{
foreach (string type in XmlTypes)
{
Assert.IsTrue(
MessageFormatFactory.CreateInputStream(new MessageFormatOptions(), type, Stream.Null)
is XmlFormatReader);
}
Assert.IsTrue(
MessageFormatFactory.CreateInputStream(new MessageFormatOptions() { DefaultContentType = "application/xml" }, null, Stream.Null)
is XmlFormatReader);
}
[Test]
public void TestWriteXmlMimeTypes()
{
foreach (string type in XmlTypes)
{
Assert.IsTrue(
MessageFormatFactory.CreateOutputStream(new MessageFormatOptions(), type, Stream.Null)
is XmlFormatWriter);
}
Assert.IsTrue(
MessageFormatFactory.CreateOutputStream(new MessageFormatOptions() { DefaultContentType = "application/xml" }, null, Stream.Null)
is XmlFormatWriter);
}
[Test]
public void TestReadProtoMimeTypes()
{
foreach (string type in ProtobufTypes)
{
Assert.IsTrue(
MessageFormatFactory.CreateInputStream(new MessageFormatOptions(), type, Stream.Null)
is CodedInputStream);
}
Assert.IsTrue(
MessageFormatFactory.CreateInputStream(new MessageFormatOptions() { DefaultContentType = "application/vnd.google.protobuf" }, null, Stream.Null)
is CodedInputStream);
}
[Test]
public void TestWriteProtoMimeTypes()
{
foreach (string type in ProtobufTypes)
{
Assert.IsTrue(
MessageFormatFactory.CreateOutputStream(new MessageFormatOptions(), type, Stream.Null)
is CodedOutputStream);
}
Assert.IsTrue(
MessageFormatFactory.CreateOutputStream(new MessageFormatOptions() { DefaultContentType = "application/vnd.google.protobuf" }, null, Stream.Null)
is CodedOutputStream);
}
[Test]
public void TestMergeFromJsonType()
{
TestXmlMessage msg = Extensions.MergeFrom(new TestXmlMessage.Builder(),
new MessageFormatOptions(), "application/json", new MemoryStream(Encoding.UTF8.GetBytes(
Extensions.ToJson(TestXmlMessage.CreateBuilder().SetText("a").SetNumber(1).Build())
)))
.Build();
Assert.AreEqual("a", msg.Text);
Assert.AreEqual(1, msg.Number);
}
[Test]
public void TestMergeFromXmlType()
{
TestXmlMessage msg = Extensions.MergeFrom(new TestXmlMessage.Builder(),
new MessageFormatOptions(), "application/xml", new MemoryStream(Encoding.UTF8.GetBytes(
Extensions.ToXml(TestXmlMessage.CreateBuilder().SetText("a").SetNumber(1).Build())
)))
.Build();
Assert.AreEqual("a", msg.Text);
Assert.AreEqual(1, msg.Number);
}
[Test]
public void TestMergeFromProtoType()
{
TestXmlMessage msg = Extensions.MergeFrom(new TestXmlMessage.Builder(),
new MessageFormatOptions(), "application/vnd.google.protobuf", new MemoryStream(
TestXmlMessage.CreateBuilder().SetText("a").SetNumber(1).Build().ToByteArray()
))
.Build();
Assert.AreEqual("a", msg.Text);
Assert.AreEqual(1, msg.Number);
}
[Test]
public void TestWriteToJsonType()
{
MemoryStream ms = new MemoryStream();
Extensions.WriteTo(TestXmlMessage.CreateBuilder().SetText("a").SetNumber(1).Build(),
new MessageFormatOptions(), "application/json", ms);
Assert.AreEqual(@"{""text"":""a"",""number"":1}", Encoding.UTF8.GetString(ms.ToArray(), 0, (int)ms.Length));
}
[Test]
public void TestWriteToXmlType()
{
MemoryStream ms = new MemoryStream();
Extensions.WriteTo(TestXmlMessage.CreateBuilder().SetText("a").SetNumber(1).Build(),
new MessageFormatOptions(), "application/xml", ms);
Assert.AreEqual("<root><text>a</text><number>1</number></root>", Encoding.UTF8.GetString(ms.ToArray(), 0, (int)ms.Length));
}
[Test]
public void TestWriteToProtoType()
{
MemoryStream ms = new MemoryStream();
Extensions.WriteTo(TestXmlMessage.CreateBuilder().SetText("a").SetNumber(1).Build(),
new MessageFormatOptions(), "application/vnd.google.protobuf", ms);
byte[] bytes = TestXmlMessage.CreateBuilder().SetText("a").SetNumber(1).Build().ToByteArray();
Assert.AreEqual(bytes, ms.ToArray());
}
[Test]
public void TestXmlReaderOptions()
{
MemoryStream ms = new MemoryStream();
XmlFormatWriter.CreateInstance(ms)
.SetOptions(XmlWriterOptions.OutputNestedArrays)
.WriteMessage("my-root-node", TestXmlMessage.CreateBuilder().SetText("a").AddNumbers(1).AddNumbers(2).Build());
ms.Position = 0;
MessageFormatOptions options = new MessageFormatOptions()
{
XmlReaderOptions = XmlReaderOptions.ReadNestedArrays,
XmlReaderRootElementName = "my-root-node"
};
TestXmlMessage msg = Extensions.MergeFrom(new TestXmlMessage.Builder(),
options, "application/xml", ms)
.Build();
Assert.AreEqual("a", msg.Text);
Assert.AreEqual(1, msg.NumbersList[0]);
Assert.AreEqual(2, msg.NumbersList[1]);
}
[Test]
public void TestXmlWriterOptions()
{
TestXmlMessage message = TestXmlMessage.CreateBuilder().SetText("a").AddNumbers(1).AddNumbers(2).Build();
MessageFormatOptions options = new MessageFormatOptions()
{
XmlWriterOptions = XmlWriterOptions.OutputNestedArrays,
XmlWriterRootElementName = "root-node"
};
MemoryStream ms = new MemoryStream();
Extensions.WriteTo(message, options, "application/xml", ms);
ms.Position = 0;
TestXmlMessage.Builder builder = TestXmlMessage.CreateBuilder();
XmlFormatReader.CreateInstance(ms)
.SetOptions(XmlReaderOptions.ReadNestedArrays)
.Merge("root-node", builder);
Assert.AreEqual("a", builder.Text);
Assert.AreEqual(1, builder.NumbersList[0]);
Assert.AreEqual(2, builder.NumbersList[1]);
}
[Test]
public void TestJsonFormatted()
{
MemoryStream ms = new MemoryStream();
Extensions.WriteTo(TestXmlMessage.CreateBuilder().SetText("a").SetNumber(1).Build(),
new MessageFormatOptions() { FormattedOutput = true }, "application/json", ms);
string expected = string.Format("{{{0} \"text\": \"a\",{0} \"number\": 1{0}}}", System.Environment.NewLine);
Assert.AreEqual(expected, Encoding.UTF8.GetString(ms.ToArray(), 0, (int)ms.Length));
}
[Test]
public void TestXmlFormatted()
{
MemoryStream ms = new MemoryStream();
Extensions.WriteTo(TestXmlMessage.CreateBuilder().SetText("a").SetNumber(1).Build(),
new MessageFormatOptions() { FormattedOutput = true }, "application/xml", ms);
Assert.AreEqual("<root>\r\n <text>a</text>\r\n <number>1</number>\r\n</root>", Encoding.UTF8.GetString(ms.ToArray(), 0, (int)ms.Length));
}
[Test]
public void TestReadCustomMimeTypes()
{
var options = new MessageFormatOptions();
//Remove existing mime-type mappings
options.MimeInputTypes.Clear();
//Add our own
options.MimeInputTypes.Add("-custom-XML-mime-type-", XmlFormatReader.CreateInstance);
Assert.AreEqual(1, options.MimeInputTypes.Count);
Stream xmlStream = new MemoryStream(Encoding.UTF8.GetBytes(
Extensions.ToXml(TestXmlMessage.CreateBuilder().SetText("a").SetNumber(1).Build())
));
TestXmlMessage msg = Extensions.MergeFrom(new TestXmlMessage.Builder(),
options, "-custom-XML-mime-type-", xmlStream)
.Build();
Assert.AreEqual("a", msg.Text);
Assert.AreEqual(1, msg.Number);
}
[Test]
public void TestWriteToCustomType()
{
var options = new MessageFormatOptions();
//Remove existing mime-type mappings
options.MimeOutputTypes.Clear();
//Add our own
options.MimeOutputTypes.Add("-custom-XML-mime-type-", XmlFormatWriter.CreateInstance);
Assert.AreEqual(1, options.MimeOutputTypes.Count);
MemoryStream ms = new MemoryStream();
Extensions.WriteTo(TestXmlMessage.CreateBuilder().SetText("a").SetNumber(1).Build(),
options, "-custom-XML-mime-type-", ms);
Assert.AreEqual("<root><text>a</text><number>1</number></root>", Encoding.UTF8.GetString(ms.ToArray(), 0, (int)ms.Length));
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -1,732 +0,0 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/unittest_drop_unknown_fields.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;
using pbd = global::Google.ProtocolBuffers.Descriptors;
using scg = global::System.Collections.Generic;
namespace Google.ProtocolBuffers.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class UnittestDropUnknownFields {
#region Extension registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
}
#endregion
#region Static variables
internal static pbd::MessageDescriptor internal__static_unittest_drop_unknown_fields_Foo__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.Foo, global::Google.ProtocolBuffers.TestProtos.Foo.Builder> internal__static_unittest_drop_unknown_fields_Foo__FieldAccessorTable;
internal static pbd::MessageDescriptor internal__static_unittest_drop_unknown_fields_FooWithExtraFields__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.FooWithExtraFields, global::Google.ProtocolBuffers.TestProtos.FooWithExtraFields.Builder> internal__static_unittest_drop_unknown_fields_FooWithExtraFields__FieldAccessorTable;
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static UnittestDropUnknownFields() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CjJnb29nbGUvcHJvdG9idWYvdW5pdHRlc3RfZHJvcF91bmtub3duX2ZpZWxk",
"cy5wcm90bxIcdW5pdHRlc3RfZHJvcF91bmtub3duX2ZpZWxkcyKFAQoDRm9v",
"EhMKC2ludDMyX3ZhbHVlGAEgASgFEkAKCmVudW1fdmFsdWUYAiABKA4yLC51",
"bml0dGVzdF9kcm9wX3Vua25vd25fZmllbGRzLkZvby5OZXN0ZWRFbnVtIicK",
"Ck5lc3RlZEVudW0SBwoDRk9PEAASBwoDQkFSEAESBwoDQkFaEAIixwEKEkZv",
"b1dpdGhFeHRyYUZpZWxkcxITCgtpbnQzMl92YWx1ZRgBIAEoBRJPCgplbnVt",
"X3ZhbHVlGAIgASgOMjsudW5pdHRlc3RfZHJvcF91bmtub3duX2ZpZWxkcy5G",
"b29XaXRoRXh0cmFGaWVsZHMuTmVzdGVkRW51bRIZChFleHRyYV9pbnQzMl92",
"YWx1ZRgDIAEoBSIwCgpOZXN0ZWRFbnVtEgcKA0ZPTxAAEgcKA0JBUhABEgcK",
"A0JBWhACEgcKA1FVWBADQjOiAgxEcm9wVW5rbm93bnOqAiFHb29nbGUuUHJv",
"dG9jb2xCdWZmZXJzLlRlc3RQcm90b3NiBnByb3RvMw=="));
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_unittest_drop_unknown_fields_Foo__Descriptor = Descriptor.MessageTypes[0];
internal__static_unittest_drop_unknown_fields_Foo__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.Foo, global::Google.ProtocolBuffers.TestProtos.Foo.Builder>(internal__static_unittest_drop_unknown_fields_Foo__Descriptor,
new string[] { "Int32Value", "EnumValue", });
internal__static_unittest_drop_unknown_fields_FooWithExtraFields__Descriptor = Descriptor.MessageTypes[1];
internal__static_unittest_drop_unknown_fields_FooWithExtraFields__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.FooWithExtraFields, global::Google.ProtocolBuffers.TestProtos.FooWithExtraFields.Builder>(internal__static_unittest_drop_unknown_fields_FooWithExtraFields__Descriptor,
new string[] { "Int32Value", "EnumValue", "ExtraInt32Value", });
pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance();
RegisterAllExtensions(registry);
return registry;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
}, assigner);
}
#endregion
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Foo : pb::GeneratedMessage<Foo, Foo.Builder> {
private Foo() { }
private static readonly Foo defaultInstance = new Foo().MakeReadOnly();
private static readonly string[] _fooFieldNames = new string[] { "enum_value", "int32_value" };
private static readonly uint[] _fooFieldTags = new uint[] { 16, 8 };
public static Foo DefaultInstance {
get { return defaultInstance; }
}
public override Foo DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override Foo ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::Google.ProtocolBuffers.TestProtos.UnittestDropUnknownFields.internal__static_unittest_drop_unknown_fields_Foo__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<Foo, Foo.Builder> InternalFieldAccessors {
get { return global::Google.ProtocolBuffers.TestProtos.UnittestDropUnknownFields.internal__static_unittest_drop_unknown_fields_Foo__FieldAccessorTable; }
}
#region Nested types
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Types {
public enum NestedEnum {
FOO = 0,
BAR = 1,
BAZ = 2,
}
}
#endregion
public const int Int32ValueFieldNumber = 1;
private int int32Value_;
public int Int32Value {
get { return int32Value_; }
}
public const int EnumValueFieldNumber = 2;
private global::Google.ProtocolBuffers.TestProtos.Foo.Types.NestedEnum enumValue_ = global::Google.ProtocolBuffers.TestProtos.Foo.Types.NestedEnum.FOO;
public global::Google.ProtocolBuffers.TestProtos.Foo.Types.NestedEnum EnumValue {
get { return enumValue_; }
}
public override void WriteTo(pb::ICodedOutputStream output) {
CalcSerializedSize();
string[] field_names = _fooFieldNames;
if (Int32Value != 0) {
output.WriteInt32(1, field_names[1], Int32Value);
}
if (EnumValue != global::Google.ProtocolBuffers.TestProtos.Foo.Types.NestedEnum.FOO) {
output.WriteEnum(2, field_names[0], (int) EnumValue, EnumValue);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
return CalcSerializedSize();
}
}
private int CalcSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (Int32Value != 0) {
size += pb::CodedOutputStream.ComputeInt32Size(1, Int32Value);
}
if (EnumValue != global::Google.ProtocolBuffers.TestProtos.Foo.Types.NestedEnum.FOO) {
size += pb::CodedOutputStream.ComputeEnumSize(2, (int) EnumValue);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
public static Foo ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static Foo ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static Foo ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static Foo ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static Foo ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static Foo ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static Foo ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static Foo ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static Foo ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static Foo ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private Foo MakeReadOnly() {
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(Foo prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<Foo, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(Foo cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private Foo result;
private Foo PrepareBuilder() {
if (resultIsReadOnly) {
Foo original = result;
result = new Foo();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override Foo MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::Google.ProtocolBuffers.TestProtos.Foo.Descriptor; }
}
public override Foo DefaultInstanceForType {
get { return global::Google.ProtocolBuffers.TestProtos.Foo.DefaultInstance; }
}
public override Foo BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is Foo) {
return MergeFrom((Foo) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(Foo other) {
if (other == global::Google.ProtocolBuffers.TestProtos.Foo.DefaultInstance) return this;
PrepareBuilder();
if (other.Int32Value != 0) {
Int32Value = other.Int32Value;
}
if (other.EnumValue != global::Google.ProtocolBuffers.TestProtos.Foo.Types.NestedEnum.FOO) {
EnumValue = other.EnumValue;
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_fooFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _fooFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 8: {
input.ReadInt32(ref result.int32Value_);
break;
}
case 16: {
object unknown;
if(input.ReadEnum(ref result.enumValue_, out unknown)) {
} else if(unknown is int) {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
unknownFields.MergeVarintField(2, (ulong)(int)unknown);
}
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public int Int32Value {
get { return result.Int32Value; }
set { SetInt32Value(value); }
}
public Builder SetInt32Value(int value) {
PrepareBuilder();
result.int32Value_ = value;
return this;
}
public Builder ClearInt32Value() {
PrepareBuilder();
result.int32Value_ = 0;
return this;
}
public global::Google.ProtocolBuffers.TestProtos.Foo.Types.NestedEnum EnumValue {
get { return result.EnumValue; }
set { SetEnumValue(value); }
}
public Builder SetEnumValue(global::Google.ProtocolBuffers.TestProtos.Foo.Types.NestedEnum value) {
PrepareBuilder();
result.enumValue_ = value;
return this;
}
public Builder ClearEnumValue() {
PrepareBuilder();
result.enumValue_ = global::Google.ProtocolBuffers.TestProtos.Foo.Types.NestedEnum.FOO;
return this;
}
}
static Foo() {
object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.UnittestDropUnknownFields.Descriptor, null);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class FooWithExtraFields : pb::GeneratedMessage<FooWithExtraFields, FooWithExtraFields.Builder> {
private FooWithExtraFields() { }
private static readonly FooWithExtraFields defaultInstance = new FooWithExtraFields().MakeReadOnly();
private static readonly string[] _fooWithExtraFieldsFieldNames = new string[] { "enum_value", "extra_int32_value", "int32_value" };
private static readonly uint[] _fooWithExtraFieldsFieldTags = new uint[] { 16, 24, 8 };
public static FooWithExtraFields DefaultInstance {
get { return defaultInstance; }
}
public override FooWithExtraFields DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override FooWithExtraFields ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::Google.ProtocolBuffers.TestProtos.UnittestDropUnknownFields.internal__static_unittest_drop_unknown_fields_FooWithExtraFields__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<FooWithExtraFields, FooWithExtraFields.Builder> InternalFieldAccessors {
get { return global::Google.ProtocolBuffers.TestProtos.UnittestDropUnknownFields.internal__static_unittest_drop_unknown_fields_FooWithExtraFields__FieldAccessorTable; }
}
#region Nested types
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Types {
public enum NestedEnum {
FOO = 0,
BAR = 1,
BAZ = 2,
QUX = 3,
}
}
#endregion
public const int Int32ValueFieldNumber = 1;
private int int32Value_;
public int Int32Value {
get { return int32Value_; }
}
public const int EnumValueFieldNumber = 2;
private global::Google.ProtocolBuffers.TestProtos.FooWithExtraFields.Types.NestedEnum enumValue_ = global::Google.ProtocolBuffers.TestProtos.FooWithExtraFields.Types.NestedEnum.FOO;
public global::Google.ProtocolBuffers.TestProtos.FooWithExtraFields.Types.NestedEnum EnumValue {
get { return enumValue_; }
}
public const int ExtraInt32ValueFieldNumber = 3;
private int extraInt32Value_;
public int ExtraInt32Value {
get { return extraInt32Value_; }
}
public override void WriteTo(pb::ICodedOutputStream output) {
CalcSerializedSize();
string[] field_names = _fooWithExtraFieldsFieldNames;
if (Int32Value != 0) {
output.WriteInt32(1, field_names[2], Int32Value);
}
if (EnumValue != global::Google.ProtocolBuffers.TestProtos.FooWithExtraFields.Types.NestedEnum.FOO) {
output.WriteEnum(2, field_names[0], (int) EnumValue, EnumValue);
}
if (ExtraInt32Value != 0) {
output.WriteInt32(3, field_names[1], ExtraInt32Value);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
return CalcSerializedSize();
}
}
private int CalcSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (Int32Value != 0) {
size += pb::CodedOutputStream.ComputeInt32Size(1, Int32Value);
}
if (EnumValue != global::Google.ProtocolBuffers.TestProtos.FooWithExtraFields.Types.NestedEnum.FOO) {
size += pb::CodedOutputStream.ComputeEnumSize(2, (int) EnumValue);
}
if (ExtraInt32Value != 0) {
size += pb::CodedOutputStream.ComputeInt32Size(3, ExtraInt32Value);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
public static FooWithExtraFields ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static FooWithExtraFields ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static FooWithExtraFields ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static FooWithExtraFields ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static FooWithExtraFields ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static FooWithExtraFields ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static FooWithExtraFields ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static FooWithExtraFields ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static FooWithExtraFields ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static FooWithExtraFields ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private FooWithExtraFields MakeReadOnly() {
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(FooWithExtraFields prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<FooWithExtraFields, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(FooWithExtraFields cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private FooWithExtraFields result;
private FooWithExtraFields PrepareBuilder() {
if (resultIsReadOnly) {
FooWithExtraFields original = result;
result = new FooWithExtraFields();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override FooWithExtraFields MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::Google.ProtocolBuffers.TestProtos.FooWithExtraFields.Descriptor; }
}
public override FooWithExtraFields DefaultInstanceForType {
get { return global::Google.ProtocolBuffers.TestProtos.FooWithExtraFields.DefaultInstance; }
}
public override FooWithExtraFields BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is FooWithExtraFields) {
return MergeFrom((FooWithExtraFields) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(FooWithExtraFields other) {
if (other == global::Google.ProtocolBuffers.TestProtos.FooWithExtraFields.DefaultInstance) return this;
PrepareBuilder();
if (other.Int32Value != 0) {
Int32Value = other.Int32Value;
}
if (other.EnumValue != global::Google.ProtocolBuffers.TestProtos.FooWithExtraFields.Types.NestedEnum.FOO) {
EnumValue = other.EnumValue;
}
if (other.ExtraInt32Value != 0) {
ExtraInt32Value = other.ExtraInt32Value;
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_fooWithExtraFieldsFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _fooWithExtraFieldsFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 8: {
input.ReadInt32(ref result.int32Value_);
break;
}
case 16: {
object unknown;
if(input.ReadEnum(ref result.enumValue_, out unknown)) {
} else if(unknown is int) {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
unknownFields.MergeVarintField(2, (ulong)(int)unknown);
}
break;
}
case 24: {
input.ReadInt32(ref result.extraInt32Value_);
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public int Int32Value {
get { return result.Int32Value; }
set { SetInt32Value(value); }
}
public Builder SetInt32Value(int value) {
PrepareBuilder();
result.int32Value_ = value;
return this;
}
public Builder ClearInt32Value() {
PrepareBuilder();
result.int32Value_ = 0;
return this;
}
public global::Google.ProtocolBuffers.TestProtos.FooWithExtraFields.Types.NestedEnum EnumValue {
get { return result.EnumValue; }
set { SetEnumValue(value); }
}
public Builder SetEnumValue(global::Google.ProtocolBuffers.TestProtos.FooWithExtraFields.Types.NestedEnum value) {
PrepareBuilder();
result.enumValue_ = value;
return this;
}
public Builder ClearEnumValue() {
PrepareBuilder();
result.enumValue_ = global::Google.ProtocolBuffers.TestProtos.FooWithExtraFields.Types.NestedEnum.FOO;
return this;
}
public int ExtraInt32Value {
get { return result.ExtraInt32Value; }
set { SetExtraInt32Value(value); }
}
public Builder SetExtraInt32Value(int value) {
PrepareBuilder();
result.extraInt32Value_ = value;
return this;
}
public Builder ClearExtraInt32Value() {
PrepareBuilder();
result.extraInt32Value_ = 0;
return this;
}
}
static FooWithExtraFields() {
object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.UnittestDropUnknownFields.Descriptor, null);
}
}
#endregion
}
#endregion Designer generated code

File diff suppressed because one or more lines are too long

@ -1,347 +0,0 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/unittest_import.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;
using pbd = global::Google.ProtocolBuffers.Descriptors;
using scg = global::System.Collections.Generic;
namespace Google.ProtocolBuffers.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class UnittestImport {
#region Extension registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
}
#endregion
#region Static variables
internal static pbd::MessageDescriptor internal__static_protobuf_unittest_import_ImportMessage__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.ImportMessage, global::Google.ProtocolBuffers.TestProtos.ImportMessage.Builder> internal__static_protobuf_unittest_import_ImportMessage__FieldAccessorTable;
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static UnittestImport() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CiVnb29nbGUvcHJvdG9idWYvdW5pdHRlc3RfaW1wb3J0LnByb3RvEhhwcm90",
"b2J1Zl91bml0dGVzdF9pbXBvcnQaLGdvb2dsZS9wcm90b2J1Zi91bml0dGVz",
"dF9pbXBvcnRfcHVibGljLnByb3RvIhoKDUltcG9ydE1lc3NhZ2USCQoBZBgB",
"IAEoBSo8CgpJbXBvcnRFbnVtEg4KCklNUE9SVF9GT08QBxIOCgpJTVBPUlRf",
"QkFSEAgSDgoKSU1QT1JUX0JBWhAJQkMKGGNvbS5nb29nbGUucHJvdG9idWYu",
"dGVzdEgB+AEBqgIhR29vZ2xlLlByb3RvY29sQnVmZmVycy5UZXN0UHJvdG9z",
"UAA="));
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_protobuf_unittest_import_ImportMessage__Descriptor = Descriptor.MessageTypes[0];
internal__static_protobuf_unittest_import_ImportMessage__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.ImportMessage, global::Google.ProtocolBuffers.TestProtos.ImportMessage.Builder>(internal__static_protobuf_unittest_import_ImportMessage__Descriptor,
new string[] { "D", });
pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance();
RegisterAllExtensions(registry);
global::Google.ProtocolBuffers.TestProtos.UnittestImportPublic.RegisterAllExtensions(registry);
return registry;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
global::Google.ProtocolBuffers.TestProtos.UnittestImportPublic.Descriptor,
}, assigner);
}
#endregion
}
#region Enums
public enum ImportEnum {
IMPORT_FOO = 7,
IMPORT_BAR = 8,
IMPORT_BAZ = 9,
}
#endregion
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class ImportMessage : pb::GeneratedMessage<ImportMessage, ImportMessage.Builder> {
private ImportMessage() { }
private static readonly ImportMessage defaultInstance = new ImportMessage().MakeReadOnly();
private static readonly string[] _importMessageFieldNames = new string[] { "d" };
private static readonly uint[] _importMessageFieldTags = new uint[] { 8 };
public static ImportMessage DefaultInstance {
get { return defaultInstance; }
}
public override ImportMessage DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override ImportMessage ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::Google.ProtocolBuffers.TestProtos.UnittestImport.internal__static_protobuf_unittest_import_ImportMessage__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<ImportMessage, ImportMessage.Builder> InternalFieldAccessors {
get { return global::Google.ProtocolBuffers.TestProtos.UnittestImport.internal__static_protobuf_unittest_import_ImportMessage__FieldAccessorTable; }
}
public const int DFieldNumber = 1;
private bool hasD;
private int d_;
public bool HasD {
get { return hasD; }
}
public int D {
get { return d_; }
}
public override bool IsInitialized {
get {
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
CalcSerializedSize();
string[] field_names = _importMessageFieldNames;
if (hasD) {
output.WriteInt32(1, field_names[0], D);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
return CalcSerializedSize();
}
}
private int CalcSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (hasD) {
size += pb::CodedOutputStream.ComputeInt32Size(1, D);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
public static ImportMessage ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static ImportMessage ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static ImportMessage ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static ImportMessage ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static ImportMessage ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static ImportMessage ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static ImportMessage ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static ImportMessage ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static ImportMessage ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static ImportMessage ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private ImportMessage MakeReadOnly() {
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(ImportMessage prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<ImportMessage, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(ImportMessage cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private ImportMessage result;
private ImportMessage PrepareBuilder() {
if (resultIsReadOnly) {
ImportMessage original = result;
result = new ImportMessage();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override ImportMessage MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::Google.ProtocolBuffers.TestProtos.ImportMessage.Descriptor; }
}
public override ImportMessage DefaultInstanceForType {
get { return global::Google.ProtocolBuffers.TestProtos.ImportMessage.DefaultInstance; }
}
public override ImportMessage BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is ImportMessage) {
return MergeFrom((ImportMessage) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(ImportMessage other) {
if (other == global::Google.ProtocolBuffers.TestProtos.ImportMessage.DefaultInstance) return this;
PrepareBuilder();
if (other.HasD) {
D = other.D;
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_importMessageFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _importMessageFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 8: {
result.hasD = input.ReadInt32(ref result.d_);
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public bool HasD {
get { return result.hasD; }
}
public int D {
get { return result.D; }
set { SetD(value); }
}
public Builder SetD(int value) {
PrepareBuilder();
result.hasD = true;
result.d_ = value;
return this;
}
public Builder ClearD() {
PrepareBuilder();
result.hasD = false;
result.d_ = 0;
return this;
}
}
static ImportMessage() {
object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.UnittestImport.Descriptor, null);
}
}
#endregion
}
#endregion Designer generated code

@ -0,0 +1,165 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/unittest_import_proto3.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbd = global::Google.Protobuf.Descriptors;
using scg = global::System.Collections.Generic;
namespace Google.Protobuf.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class UnittestImportProto3 {
#region Static variables
internal static pbd::MessageDescriptor internal__static_protobuf_unittest_import_ImportMessage__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Google.Protobuf.TestProtos.ImportMessage> internal__static_protobuf_unittest_import_ImportMessage__FieldAccessorTable;
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static UnittestImportProto3() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cixnb29nbGUvcHJvdG9idWYvdW5pdHRlc3RfaW1wb3J0X3Byb3RvMy5wcm90",
"bxIYcHJvdG9idWZfdW5pdHRlc3RfaW1wb3J0GjNnb29nbGUvcHJvdG9idWYv",
"dW5pdHRlc3RfaW1wb3J0X3B1YmxpY19wcm90bzMucHJvdG8iGgoNSW1wb3J0",
"TWVzc2FnZRIJCgFkGAEgASgFKlkKCkltcG9ydEVudW0SGwoXSU1QT1JUX0VO",
"VU1fVU5TUEVDSUZJRUQQABIOCgpJTVBPUlRfRk9PEAcSDgoKSU1QT1JUX0JB",
"UhAIEg4KCklNUE9SVF9CQVoQCUI8Chhjb20uZ29vZ2xlLnByb3RvYnVmLnRl",
"c3RIAfgBAaoCGkdvb2dsZS5Qcm90b2J1Zi5UZXN0UHJvdG9zUABiBnByb3Rv",
"Mw=="));
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_protobuf_unittest_import_ImportMessage__Descriptor = Descriptor.MessageTypes[0];
internal__static_protobuf_unittest_import_ImportMessage__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.Protobuf.TestProtos.ImportMessage>(internal__static_protobuf_unittest_import_ImportMessage__Descriptor,
new string[] { "D", });
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
global::Google.Protobuf.TestProtos.UnittestImportPublicProto3.Descriptor,
}, assigner);
}
#endregion
}
#region Enums
public enum ImportEnum : long {
IMPORT_ENUM_UNSPECIFIED = 0,
IMPORT_FOO = 7,
IMPORT_BAR = 8,
IMPORT_BAZ = 9,
}
#endregion
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class ImportMessage : pb::IMessage<ImportMessage>, global::System.IEquatable<ImportMessage> {
private static readonly pb::MessageParser<ImportMessage> _parser = new pb::MessageParser<ImportMessage>(() => new ImportMessage());
public static pb::MessageParser<ImportMessage> Parser { get { return _parser; } }
private static readonly string[] _fieldNames = new string[] { "d" };
private static readonly uint[] _fieldTags = new uint[] { 8 };
public static pbd::MessageDescriptor Descriptor {
get { return global::Google.Protobuf.TestProtos.UnittestImportProto3.internal__static_protobuf_unittest_import_ImportMessage__Descriptor; }
}
public pb::FieldAccess.FieldAccessorTable<ImportMessage> Fields {
get { return global::Google.Protobuf.TestProtos.UnittestImportProto3.internal__static_protobuf_unittest_import_ImportMessage__FieldAccessorTable; }
}
public ImportMessage() { }
public ImportMessage(ImportMessage other) {
MergeFrom(other);
}
public const int DFieldNumber = 1;
private int d_;
public int D {
get { return d_; }
set { d_ = value; }
}
public override bool Equals(object other) {
return Equals(other as ImportMessage);
}
public bool Equals(ImportMessage other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (D != other.D) return false;
return true;
}
public override int GetHashCode() {
int hash = 0;
if (D != 0) hash ^= D.GetHashCode();
return hash;
}
public void WriteTo(pb::ICodedOutputStream output) {
string[] fieldNames = _fieldNames;
if (D != 0) {
output.WriteInt32(1, fieldNames[0], D);
}
}
public int CalculateSize() {
int size = 0;
if (D != 0) {
size += pb::CodedOutputStream.ComputeInt32Size(1, D);
}
return size;
}
public void MergeFrom(ImportMessage other) {
if (other == null) {
return;
}
if (other.D != 0) {
D = other.D;
}
}
public void MergeFrom(pb::ICodedInputStream input) {
uint tag;
string fieldName;
while (input.ReadTag(out tag, out fieldName)) {
if (tag == 0 && fieldName != null) {
int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal);
if (fieldOrdinal >= 0) {
tag = _fieldTags[fieldOrdinal];
}
}
switch(tag) {
case 0:
throw pb::InvalidProtocolBufferException.InvalidTag();
default:
if (pb::WireFormat.IsEndGroupTag(tag)) {
return;
}
break;
case 8: {
input.ReadInt32(ref d_);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code

@ -1,333 +0,0 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/unittest_import_public.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;
using pbd = global::Google.ProtocolBuffers.Descriptors;
using scg = global::System.Collections.Generic;
namespace Google.ProtocolBuffers.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class UnittestImportPublic {
#region Extension registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
}
#endregion
#region Static variables
internal static pbd::MessageDescriptor internal__static_protobuf_unittest_import_PublicImportMessage__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.PublicImportMessage, global::Google.ProtocolBuffers.TestProtos.PublicImportMessage.Builder> internal__static_protobuf_unittest_import_PublicImportMessage__FieldAccessorTable;
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static UnittestImportPublic() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cixnb29nbGUvcHJvdG9idWYvdW5pdHRlc3RfaW1wb3J0X3B1YmxpYy5wcm90",
"bxIYcHJvdG9idWZfdW5pdHRlc3RfaW1wb3J0IiAKE1B1YmxpY0ltcG9ydE1l",
"c3NhZ2USCQoBZRgBIAEoBUI+Chhjb20uZ29vZ2xlLnByb3RvYnVmLnRlc3Sq",
"AiFHb29nbGUuUHJvdG9jb2xCdWZmZXJzLlRlc3RQcm90b3M="));
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_protobuf_unittest_import_PublicImportMessage__Descriptor = Descriptor.MessageTypes[0];
internal__static_protobuf_unittest_import_PublicImportMessage__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.PublicImportMessage, global::Google.ProtocolBuffers.TestProtos.PublicImportMessage.Builder>(internal__static_protobuf_unittest_import_PublicImportMessage__Descriptor,
new string[] { "E", });
pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance();
RegisterAllExtensions(registry);
return registry;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
}, assigner);
}
#endregion
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class PublicImportMessage : pb::GeneratedMessage<PublicImportMessage, PublicImportMessage.Builder> {
private PublicImportMessage() { }
private static readonly PublicImportMessage defaultInstance = new PublicImportMessage().MakeReadOnly();
private static readonly string[] _publicImportMessageFieldNames = new string[] { "e" };
private static readonly uint[] _publicImportMessageFieldTags = new uint[] { 8 };
public static PublicImportMessage DefaultInstance {
get { return defaultInstance; }
}
public override PublicImportMessage DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override PublicImportMessage ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::Google.ProtocolBuffers.TestProtos.UnittestImportPublic.internal__static_protobuf_unittest_import_PublicImportMessage__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<PublicImportMessage, PublicImportMessage.Builder> InternalFieldAccessors {
get { return global::Google.ProtocolBuffers.TestProtos.UnittestImportPublic.internal__static_protobuf_unittest_import_PublicImportMessage__FieldAccessorTable; }
}
public const int EFieldNumber = 1;
private bool hasE;
private int e_;
public bool HasE {
get { return hasE; }
}
public int E {
get { return e_; }
}
public override bool IsInitialized {
get {
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
CalcSerializedSize();
string[] field_names = _publicImportMessageFieldNames;
if (hasE) {
output.WriteInt32(1, field_names[0], E);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
return CalcSerializedSize();
}
}
private int CalcSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (hasE) {
size += pb::CodedOutputStream.ComputeInt32Size(1, E);
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
public static PublicImportMessage ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static PublicImportMessage ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static PublicImportMessage ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static PublicImportMessage ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static PublicImportMessage ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static PublicImportMessage ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static PublicImportMessage ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static PublicImportMessage ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static PublicImportMessage ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static PublicImportMessage ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private PublicImportMessage MakeReadOnly() {
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(PublicImportMessage prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<PublicImportMessage, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(PublicImportMessage cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private PublicImportMessage result;
private PublicImportMessage PrepareBuilder() {
if (resultIsReadOnly) {
PublicImportMessage original = result;
result = new PublicImportMessage();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override PublicImportMessage MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::Google.ProtocolBuffers.TestProtos.PublicImportMessage.Descriptor; }
}
public override PublicImportMessage DefaultInstanceForType {
get { return global::Google.ProtocolBuffers.TestProtos.PublicImportMessage.DefaultInstance; }
}
public override PublicImportMessage BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is PublicImportMessage) {
return MergeFrom((PublicImportMessage) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(PublicImportMessage other) {
if (other == global::Google.ProtocolBuffers.TestProtos.PublicImportMessage.DefaultInstance) return this;
PrepareBuilder();
if (other.HasE) {
E = other.E;
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_publicImportMessageFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _publicImportMessageFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 8: {
result.hasE = input.ReadInt32(ref result.e_);
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public bool HasE {
get { return result.hasE; }
}
public int E {
get { return result.E; }
set { SetE(value); }
}
public Builder SetE(int value) {
PrepareBuilder();
result.hasE = true;
result.e_ = value;
return this;
}
public Builder ClearE() {
PrepareBuilder();
result.hasE = false;
result.e_ = 0;
return this;
}
}
static PublicImportMessage() {
object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.UnittestImportPublic.Descriptor, null);
}
}
#endregion
}
#endregion Designer generated code

@ -0,0 +1,150 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/unittest_import_public_proto3.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbd = global::Google.Protobuf.Descriptors;
using scg = global::System.Collections.Generic;
namespace Google.Protobuf.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class UnittestImportPublicProto3 {
#region Static variables
internal static pbd::MessageDescriptor internal__static_protobuf_unittest_import_PublicImportMessage__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Google.Protobuf.TestProtos.PublicImportMessage> internal__static_protobuf_unittest_import_PublicImportMessage__FieldAccessorTable;
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static UnittestImportPublicProto3() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CjNnb29nbGUvcHJvdG9idWYvdW5pdHRlc3RfaW1wb3J0X3B1YmxpY19wcm90",
"bzMucHJvdG8SGHByb3RvYnVmX3VuaXR0ZXN0X2ltcG9ydCIgChNQdWJsaWNJ",
"bXBvcnRNZXNzYWdlEgkKAWUYASABKAVCNwoYY29tLmdvb2dsZS5wcm90b2J1",
"Zi50ZXN0qgIaR29vZ2xlLlByb3RvYnVmLlRlc3RQcm90b3NiBnByb3RvMw=="));
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_protobuf_unittest_import_PublicImportMessage__Descriptor = Descriptor.MessageTypes[0];
internal__static_protobuf_unittest_import_PublicImportMessage__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.Protobuf.TestProtos.PublicImportMessage>(internal__static_protobuf_unittest_import_PublicImportMessage__Descriptor,
new string[] { "E", });
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
}, assigner);
}
#endregion
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class PublicImportMessage : pb::IMessage<PublicImportMessage>, global::System.IEquatable<PublicImportMessage> {
private static readonly pb::MessageParser<PublicImportMessage> _parser = new pb::MessageParser<PublicImportMessage>(() => new PublicImportMessage());
public static pb::MessageParser<PublicImportMessage> Parser { get { return _parser; } }
private static readonly string[] _fieldNames = new string[] { "e" };
private static readonly uint[] _fieldTags = new uint[] { 8 };
public static pbd::MessageDescriptor Descriptor {
get { return global::Google.Protobuf.TestProtos.UnittestImportPublicProto3.internal__static_protobuf_unittest_import_PublicImportMessage__Descriptor; }
}
public pb::FieldAccess.FieldAccessorTable<PublicImportMessage> Fields {
get { return global::Google.Protobuf.TestProtos.UnittestImportPublicProto3.internal__static_protobuf_unittest_import_PublicImportMessage__FieldAccessorTable; }
}
public PublicImportMessage() { }
public PublicImportMessage(PublicImportMessage other) {
MergeFrom(other);
}
public const int EFieldNumber = 1;
private int e_;
public int E {
get { return e_; }
set { e_ = value; }
}
public override bool Equals(object other) {
return Equals(other as PublicImportMessage);
}
public bool Equals(PublicImportMessage other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (E != other.E) return false;
return true;
}
public override int GetHashCode() {
int hash = 0;
if (E != 0) hash ^= E.GetHashCode();
return hash;
}
public void WriteTo(pb::ICodedOutputStream output) {
string[] fieldNames = _fieldNames;
if (E != 0) {
output.WriteInt32(1, fieldNames[0], E);
}
}
public int CalculateSize() {
int size = 0;
if (E != 0) {
size += pb::CodedOutputStream.ComputeInt32Size(1, E);
}
return size;
}
public void MergeFrom(PublicImportMessage other) {
if (other == null) {
return;
}
if (other.E != 0) {
E = other.E;
}
}
public void MergeFrom(pb::ICodedInputStream input) {
uint tag;
string fieldName;
while (input.ReadTag(out tag, out fieldName)) {
if (tag == 0 && fieldName != null) {
int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal);
if (fieldOrdinal >= 0) {
tag = _fieldTags[fieldOrdinal];
}
}
switch(tag) {
case 0:
throw pb::InvalidProtocolBufferException.InvalidTag();
default:
if (pb::WireFormat.IsEndGroupTag(tag)) {
return;
}
break;
case 8: {
input.ReadInt32(ref e_);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -1,738 +0,0 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/unittest_optimize_for.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;
using pbd = global::Google.ProtocolBuffers.Descriptors;
using scg = global::System.Collections.Generic;
namespace Google.ProtocolBuffers.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class UnittestOptimizeFor {
#region Extension registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
registry.Add(global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize.TestExtension);
registry.Add(global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize.TestExtension2);
}
#endregion
#region Static variables
internal static pbd::MessageDescriptor internal__static_protobuf_unittest_TestOptimizedForSize__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize, global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize.Builder> internal__static_protobuf_unittest_TestOptimizedForSize__FieldAccessorTable;
internal static pbd::MessageDescriptor internal__static_protobuf_unittest_TestRequiredOptimizedForSize__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize, global::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize.Builder> internal__static_protobuf_unittest_TestRequiredOptimizedForSize__FieldAccessorTable;
internal static pbd::MessageDescriptor internal__static_protobuf_unittest_TestOptionalOptimizedForSize__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.TestOptionalOptimizedForSize, global::Google.ProtocolBuffers.TestProtos.TestOptionalOptimizedForSize.Builder> internal__static_protobuf_unittest_TestOptionalOptimizedForSize__FieldAccessorTable;
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static UnittestOptimizeFor() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Citnb29nbGUvcHJvdG9idWYvdW5pdHRlc3Rfb3B0aW1pemVfZm9yLnByb3Rv",
"EhFwcm90b2J1Zl91bml0dGVzdBoeZ29vZ2xlL3Byb3RvYnVmL3VuaXR0ZXN0",
"LnByb3RvIsoCChRUZXN0T3B0aW1pemVkRm9yU2l6ZRIJCgFpGAEgASgFEi4K",
"A21zZxgTIAEoCzIhLnByb3RvYnVmX3VuaXR0ZXN0LkZvcmVpZ25NZXNzYWdl",
"EhcKDWludGVnZXJfZmllbGQYAiABKAVIABIWCgxzdHJpbmdfZmllbGQYAyAB",
"KAlIACoJCOgHEICAgIACMkAKDnRlc3RfZXh0ZW5zaW9uEicucHJvdG9idWZf",
"dW5pdHRlc3QuVGVzdE9wdGltaXplZEZvclNpemUY0gkgASgFMnIKD3Rlc3Rf",
"ZXh0ZW5zaW9uMhInLnByb3RvYnVmX3VuaXR0ZXN0LlRlc3RPcHRpbWl6ZWRG",
"b3JTaXplGNMJIAEoCzIvLnByb3RvYnVmX3VuaXR0ZXN0LlRlc3RSZXF1aXJl",
"ZE9wdGltaXplZEZvclNpemVCBQoDZm9vIikKHFRlc3RSZXF1aXJlZE9wdGlt",
"aXplZEZvclNpemUSCQoBeBgBIAIoBSJaChxUZXN0T3B0aW9uYWxPcHRpbWl6",
"ZWRGb3JTaXplEjoKAW8YASABKAsyLy5wcm90b2J1Zl91bml0dGVzdC5UZXN0",
"UmVxdWlyZWRPcHRpbWl6ZWRGb3JTaXplQiZIAqoCIUdvb2dsZS5Qcm90b2Nv",
"bEJ1ZmZlcnMuVGVzdFByb3Rvcw=="));
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_protobuf_unittest_TestOptimizedForSize__Descriptor = Descriptor.MessageTypes[0];
internal__static_protobuf_unittest_TestOptimizedForSize__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize, global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize.Builder>(internal__static_protobuf_unittest_TestOptimizedForSize__Descriptor,
new string[] { "I", "Msg", "IntegerField", "StringField", "Foo", });
global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize.TestExtension = pb::GeneratedSingleExtension<int>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize.Descriptor.Extensions[0]);
global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize.TestExtension2 = pb::GeneratedSingleExtension<global::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize.Descriptor.Extensions[1]);
internal__static_protobuf_unittest_TestRequiredOptimizedForSize__Descriptor = Descriptor.MessageTypes[1];
internal__static_protobuf_unittest_TestRequiredOptimizedForSize__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize, global::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize.Builder>(internal__static_protobuf_unittest_TestRequiredOptimizedForSize__Descriptor,
new string[] { "X", });
internal__static_protobuf_unittest_TestOptionalOptimizedForSize__Descriptor = Descriptor.MessageTypes[2];
internal__static_protobuf_unittest_TestOptionalOptimizedForSize__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.TestOptionalOptimizedForSize, global::Google.ProtocolBuffers.TestProtos.TestOptionalOptimizedForSize.Builder>(internal__static_protobuf_unittest_TestOptionalOptimizedForSize__Descriptor,
new string[] { "O", });
pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance();
RegisterAllExtensions(registry);
global::Google.ProtocolBuffers.TestProtos.Unittest.RegisterAllExtensions(registry);
return registry;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
global::Google.ProtocolBuffers.TestProtos.Unittest.Descriptor,
}, assigner);
}
#endregion
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class TestOptimizedForSize : pb::ExtendableMessage<TestOptimizedForSize, TestOptimizedForSize.Builder> {
private TestOptimizedForSize() { }
private static readonly TestOptimizedForSize defaultInstance = new TestOptimizedForSize().MakeReadOnly();
public static TestOptimizedForSize DefaultInstance {
get { return defaultInstance; }
}
public override TestOptimizedForSize DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override TestOptimizedForSize ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::Google.ProtocolBuffers.TestProtos.UnittestOptimizeFor.internal__static_protobuf_unittest_TestOptimizedForSize__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<TestOptimizedForSize, TestOptimizedForSize.Builder> InternalFieldAccessors {
get { return global::Google.ProtocolBuffers.TestProtos.UnittestOptimizeFor.internal__static_protobuf_unittest_TestOptimizedForSize__FieldAccessorTable; }
}
public const int TestExtensionFieldNumber = 1234;
public static pb::GeneratedExtensionBase<int> TestExtension;
public const int TestExtension2FieldNumber = 1235;
public static pb::GeneratedExtensionBase<global::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize> TestExtension2;
private object foo_;
public enum FooOneofCase {
IntegerField = 2,
StringField = 3,
None = 0,
}
private FooOneofCase fooCase_ = FooOneofCase.None;
public FooOneofCase FooCase {
get { return fooCase_; }
}
public const int IFieldNumber = 1;
private bool hasI;
private int i_;
public bool HasI {
get { return hasI; }
}
public int I {
get { return i_; }
}
public const int MsgFieldNumber = 19;
private bool hasMsg;
private global::Google.ProtocolBuffers.TestProtos.ForeignMessage msg_;
public bool HasMsg {
get { return hasMsg; }
}
public global::Google.ProtocolBuffers.TestProtos.ForeignMessage Msg {
get { return msg_ ?? global::Google.ProtocolBuffers.TestProtos.ForeignMessage.DefaultInstance; }
}
public const int IntegerFieldFieldNumber = 2;
public bool HasIntegerField {
get { return fooCase_ == FooOneofCase.IntegerField; }
}
public int IntegerField {
get { return fooCase_ == FooOneofCase.IntegerField ? (int) foo_ : 0; }
}
public const int StringFieldFieldNumber = 3;
public bool HasStringField {
get { return fooCase_ == FooOneofCase.StringField; }
}
public string StringField {
get { return fooCase_ == FooOneofCase.StringField ? (string) foo_ : ""; }
}
public static TestOptimizedForSize ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static TestOptimizedForSize ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static TestOptimizedForSize ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static TestOptimizedForSize ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static TestOptimizedForSize ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static TestOptimizedForSize ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static TestOptimizedForSize ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static TestOptimizedForSize ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static TestOptimizedForSize ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static TestOptimizedForSize ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private TestOptimizedForSize MakeReadOnly() {
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(TestOptimizedForSize prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::ExtendableBuilder<TestOptimizedForSize, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(TestOptimizedForSize cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private TestOptimizedForSize result;
private TestOptimizedForSize PrepareBuilder() {
if (resultIsReadOnly) {
TestOptimizedForSize original = result;
result = new TestOptimizedForSize();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override TestOptimizedForSize MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize.Descriptor; }
}
public override TestOptimizedForSize DefaultInstanceForType {
get { return global::Google.ProtocolBuffers.TestProtos.TestOptimizedForSize.DefaultInstance; }
}
public override TestOptimizedForSize BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public bool HasI {
get { return result.hasI; }
}
public int I {
get { return result.I; }
set { SetI(value); }
}
public Builder SetI(int value) {
PrepareBuilder();
result.hasI = true;
result.i_ = value;
return this;
}
public Builder ClearI() {
PrepareBuilder();
result.hasI = false;
result.i_ = 0;
return this;
}
public bool HasMsg {
get { return result.hasMsg; }
}
public global::Google.ProtocolBuffers.TestProtos.ForeignMessage Msg {
get { return result.Msg; }
set { SetMsg(value); }
}
public Builder SetMsg(global::Google.ProtocolBuffers.TestProtos.ForeignMessage value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasMsg = true;
result.msg_ = value;
return this;
}
public Builder SetMsg(global::Google.ProtocolBuffers.TestProtos.ForeignMessage.Builder builderForValue) {
pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue");
PrepareBuilder();
result.hasMsg = true;
result.msg_ = builderForValue.Build();
return this;
}
public Builder MergeMsg(global::Google.ProtocolBuffers.TestProtos.ForeignMessage value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
if (result.hasMsg &&
result.msg_ != global::Google.ProtocolBuffers.TestProtos.ForeignMessage.DefaultInstance) {
result.msg_ = global::Google.ProtocolBuffers.TestProtos.ForeignMessage.CreateBuilder(result.msg_).MergeFrom(value).BuildPartial();
} else {
result.msg_ = value;
}
result.hasMsg = true;
return this;
}
public Builder ClearMsg() {
PrepareBuilder();
result.hasMsg = false;
result.msg_ = null;
return this;
}
public bool HasIntegerField {
get { return result.fooCase_ == FooOneofCase.IntegerField; }
}
public int IntegerField {
get { return result.fooCase_ == FooOneofCase.IntegerField ? (int) result.foo_ : 0; }
set { SetIntegerField(value); }
}
public Builder SetIntegerField(int value) {
PrepareBuilder();
result.foo_ = value;
result.fooCase_ = FooOneofCase.IntegerField;
return this;
}
public Builder ClearIntegerField() {
PrepareBuilder();
if (result.fooCase_ == FooOneofCase.IntegerField) {
result.fooCase_ = FooOneofCase.None;
}
return this;
}
public bool HasStringField {
get { return result.fooCase_ == FooOneofCase.StringField; }
}
public string StringField {
get { return result.fooCase_ == FooOneofCase.StringField ? (string) result.foo_ : ""; }
set { SetStringField(value); }
}
public Builder SetStringField(string value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.foo_ = value;
result.fooCase_ = FooOneofCase.StringField;
return this;
}
public Builder ClearStringField() {
PrepareBuilder();
if (result.fooCase_ == FooOneofCase.StringField) {
result.fooCase_ = FooOneofCase.None;
}
return this;
}
public FooOneofCase FooCase {
get { return result.fooCase_; }
}
public Builder ClearFoo() {
PrepareBuilder();
result.foo_ = null;
result.fooCase_ = FooOneofCase.None;
return this;
}
}
static TestOptimizedForSize() {
object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.UnittestOptimizeFor.Descriptor, null);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class TestRequiredOptimizedForSize : pb::GeneratedMessage<TestRequiredOptimizedForSize, TestRequiredOptimizedForSize.Builder> {
private TestRequiredOptimizedForSize() { }
private static readonly TestRequiredOptimizedForSize defaultInstance = new TestRequiredOptimizedForSize().MakeReadOnly();
public static TestRequiredOptimizedForSize DefaultInstance {
get { return defaultInstance; }
}
public override TestRequiredOptimizedForSize DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override TestRequiredOptimizedForSize ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::Google.ProtocolBuffers.TestProtos.UnittestOptimizeFor.internal__static_protobuf_unittest_TestRequiredOptimizedForSize__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<TestRequiredOptimizedForSize, TestRequiredOptimizedForSize.Builder> InternalFieldAccessors {
get { return global::Google.ProtocolBuffers.TestProtos.UnittestOptimizeFor.internal__static_protobuf_unittest_TestRequiredOptimizedForSize__FieldAccessorTable; }
}
public const int XFieldNumber = 1;
private bool hasX;
private int x_;
public bool HasX {
get { return hasX; }
}
public int X {
get { return x_; }
}
public static TestRequiredOptimizedForSize ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static TestRequiredOptimizedForSize ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static TestRequiredOptimizedForSize ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static TestRequiredOptimizedForSize ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static TestRequiredOptimizedForSize ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static TestRequiredOptimizedForSize ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static TestRequiredOptimizedForSize ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static TestRequiredOptimizedForSize ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static TestRequiredOptimizedForSize ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static TestRequiredOptimizedForSize ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private TestRequiredOptimizedForSize MakeReadOnly() {
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(TestRequiredOptimizedForSize prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<TestRequiredOptimizedForSize, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(TestRequiredOptimizedForSize cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private TestRequiredOptimizedForSize result;
private TestRequiredOptimizedForSize PrepareBuilder() {
if (resultIsReadOnly) {
TestRequiredOptimizedForSize original = result;
result = new TestRequiredOptimizedForSize();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override TestRequiredOptimizedForSize MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize.Descriptor; }
}
public override TestRequiredOptimizedForSize DefaultInstanceForType {
get { return global::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize.DefaultInstance; }
}
public override TestRequiredOptimizedForSize BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public bool HasX {
get { return result.hasX; }
}
public int X {
get { return result.X; }
set { SetX(value); }
}
public Builder SetX(int value) {
PrepareBuilder();
result.hasX = true;
result.x_ = value;
return this;
}
public Builder ClearX() {
PrepareBuilder();
result.hasX = false;
result.x_ = 0;
return this;
}
}
static TestRequiredOptimizedForSize() {
object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.UnittestOptimizeFor.Descriptor, null);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class TestOptionalOptimizedForSize : pb::GeneratedMessage<TestOptionalOptimizedForSize, TestOptionalOptimizedForSize.Builder> {
private TestOptionalOptimizedForSize() { }
private static readonly TestOptionalOptimizedForSize defaultInstance = new TestOptionalOptimizedForSize().MakeReadOnly();
public static TestOptionalOptimizedForSize DefaultInstance {
get { return defaultInstance; }
}
public override TestOptionalOptimizedForSize DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override TestOptionalOptimizedForSize ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::Google.ProtocolBuffers.TestProtos.UnittestOptimizeFor.internal__static_protobuf_unittest_TestOptionalOptimizedForSize__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<TestOptionalOptimizedForSize, TestOptionalOptimizedForSize.Builder> InternalFieldAccessors {
get { return global::Google.ProtocolBuffers.TestProtos.UnittestOptimizeFor.internal__static_protobuf_unittest_TestOptionalOptimizedForSize__FieldAccessorTable; }
}
public const int OFieldNumber = 1;
private bool hasO;
private global::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize o_;
public bool HasO {
get { return hasO; }
}
public global::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize O {
get { return o_ ?? global::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize.DefaultInstance; }
}
public static TestOptionalOptimizedForSize ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static TestOptionalOptimizedForSize ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static TestOptionalOptimizedForSize ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static TestOptionalOptimizedForSize ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static TestOptionalOptimizedForSize ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static TestOptionalOptimizedForSize ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static TestOptionalOptimizedForSize ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static TestOptionalOptimizedForSize ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static TestOptionalOptimizedForSize ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static TestOptionalOptimizedForSize ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private TestOptionalOptimizedForSize MakeReadOnly() {
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(TestOptionalOptimizedForSize prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<TestOptionalOptimizedForSize, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(TestOptionalOptimizedForSize cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private TestOptionalOptimizedForSize result;
private TestOptionalOptimizedForSize PrepareBuilder() {
if (resultIsReadOnly) {
TestOptionalOptimizedForSize original = result;
result = new TestOptionalOptimizedForSize();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override TestOptionalOptimizedForSize MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::Google.ProtocolBuffers.TestProtos.TestOptionalOptimizedForSize.Descriptor; }
}
public override TestOptionalOptimizedForSize DefaultInstanceForType {
get { return global::Google.ProtocolBuffers.TestProtos.TestOptionalOptimizedForSize.DefaultInstance; }
}
public override TestOptionalOptimizedForSize BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public bool HasO {
get { return result.hasO; }
}
public global::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize O {
get { return result.O; }
set { SetO(value); }
}
public Builder SetO(global::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
result.hasO = true;
result.o_ = value;
return this;
}
public Builder SetO(global::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize.Builder builderForValue) {
pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue");
PrepareBuilder();
result.hasO = true;
result.o_ = builderForValue.Build();
return this;
}
public Builder MergeO(global::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize value) {
pb::ThrowHelper.ThrowIfNull(value, "value");
PrepareBuilder();
if (result.hasO &&
result.o_ != global::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize.DefaultInstance) {
result.o_ = global::Google.ProtocolBuffers.TestProtos.TestRequiredOptimizedForSize.CreateBuilder(result.o_).MergeFrom(value).BuildPartial();
} else {
result.o_ = value;
}
result.hasO = true;
return this;
}
public Builder ClearO() {
PrepareBuilder();
result.hasO = false;
result.o_ = null;
return this;
}
}
static TestOptionalOptimizedForSize() {
object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.UnittestOptimizeFor.Descriptor, null);
}
}
#endregion
}
#endregion Designer generated code

File diff suppressed because it is too large Load Diff

@ -1,809 +0,0 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/unknown_enum_test.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;
using pbd = global::Google.ProtocolBuffers.Descriptors;
using scg = global::System.Collections.Generic;
namespace Google.ProtocolBuffers.TestProtos {
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class UnknownEnumTest {
#region Extension registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
}
#endregion
#region Static variables
internal static pbd::MessageDescriptor internal__static_google_protobuf_util_DownRevision__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.DownRevision, global::Google.ProtocolBuffers.TestProtos.DownRevision.Builder> internal__static_google_protobuf_util_DownRevision__FieldAccessorTable;
internal static pbd::MessageDescriptor internal__static_google_protobuf_util_UpRevision__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.UpRevision, global::Google.ProtocolBuffers.TestProtos.UpRevision.Builder> internal__static_google_protobuf_util_UpRevision__FieldAccessorTable;
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static UnknownEnumTest() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cidnb29nbGUvcHJvdG9idWYvdW5rbm93bl9lbnVtX3Rlc3QucHJvdG8SFGdv",
"b2dsZS5wcm90b2J1Zi51dGlsIr8BCgxEb3duUmV2aXNpb24SRQoFdmFsdWUY",
"ASABKA4yJy5nb29nbGUucHJvdG9idWYudXRpbC5Eb3duUmV2aXNpb24uRW51",
"bToNREVGQVVMVF9WQUxVRRI3CgZ2YWx1ZXMYAiADKA4yJy5nb29nbGUucHJv",
"dG9idWYudXRpbC5Eb3duUmV2aXNpb24uRW51bSIvCgRFbnVtEhEKDURFRkFV",
"TFRfVkFMVUUQAhIUChBOT05ERUZBVUxUX1ZBTFVFEAMi6gEKClVwUmV2aXNp",
"b24SQwoFdmFsdWUYASABKA4yJS5nb29nbGUucHJvdG9idWYudXRpbC5VcFJl",
"dmlzaW9uLkVudW06DURFRkFVTFRfVkFMVUUSNQoGdmFsdWVzGAIgAygOMiUu",
"Z29vZ2xlLnByb3RvYnVmLnV0aWwuVXBSZXZpc2lvbi5FbnVtImAKBEVudW0S",
"EQoNREVGQVVMVF9WQUxVRRACEhQKEE5PTkRFRkFVTFRfVkFMVUUQAxINCglO",
"RVdfVkFMVUUQBBIPCgtORVdfVkFMVUVfMhAFEg8KC05FV19WQUxVRV8zEAZC",
"JKoCIUdvb2dsZS5Qcm90b2NvbEJ1ZmZlcnMuVGVzdFByb3Rvcw=="));
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_google_protobuf_util_DownRevision__Descriptor = Descriptor.MessageTypes[0];
internal__static_google_protobuf_util_DownRevision__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.DownRevision, global::Google.ProtocolBuffers.TestProtos.DownRevision.Builder>(internal__static_google_protobuf_util_DownRevision__Descriptor,
new string[] { "Value", "Values", });
internal__static_google_protobuf_util_UpRevision__Descriptor = Descriptor.MessageTypes[1];
internal__static_google_protobuf_util_UpRevision__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.UpRevision, global::Google.ProtocolBuffers.TestProtos.UpRevision.Builder>(internal__static_google_protobuf_util_UpRevision__Descriptor,
new string[] { "Value", "Values", });
pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance();
RegisterAllExtensions(registry);
return registry;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
}, assigner);
}
#endregion
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class DownRevision : pb::GeneratedMessage<DownRevision, DownRevision.Builder> {
private DownRevision() { }
private static readonly DownRevision defaultInstance = new DownRevision().MakeReadOnly();
private static readonly string[] _downRevisionFieldNames = new string[] { "value", "values" };
private static readonly uint[] _downRevisionFieldTags = new uint[] { 8, 16 };
public static DownRevision DefaultInstance {
get { return defaultInstance; }
}
public override DownRevision DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override DownRevision ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::Google.ProtocolBuffers.TestProtos.UnknownEnumTest.internal__static_google_protobuf_util_DownRevision__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<DownRevision, DownRevision.Builder> InternalFieldAccessors {
get { return global::Google.ProtocolBuffers.TestProtos.UnknownEnumTest.internal__static_google_protobuf_util_DownRevision__FieldAccessorTable; }
}
#region Nested types
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Types {
public enum Enum {
DEFAULT_VALUE = 2,
NONDEFAULT_VALUE = 3,
}
}
#endregion
public const int ValueFieldNumber = 1;
private bool hasValue;
private global::Google.ProtocolBuffers.TestProtos.DownRevision.Types.Enum value_ = global::Google.ProtocolBuffers.TestProtos.DownRevision.Types.Enum.DEFAULT_VALUE;
public bool HasValue {
get { return hasValue; }
}
public global::Google.ProtocolBuffers.TestProtos.DownRevision.Types.Enum Value {
get { return value_; }
}
public const int ValuesFieldNumber = 2;
private pbc::PopsicleList<global::Google.ProtocolBuffers.TestProtos.DownRevision.Types.Enum> values_ = new pbc::PopsicleList<global::Google.ProtocolBuffers.TestProtos.DownRevision.Types.Enum>();
public scg::IList<global::Google.ProtocolBuffers.TestProtos.DownRevision.Types.Enum> ValuesList {
get { return pbc::Lists.AsReadOnly(values_); }
}
public int ValuesCount {
get { return values_.Count; }
}
public global::Google.ProtocolBuffers.TestProtos.DownRevision.Types.Enum GetValues(int index) {
return values_[index];
}
public override bool IsInitialized {
get {
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
CalcSerializedSize();
string[] field_names = _downRevisionFieldNames;
if (hasValue) {
output.WriteEnum(1, field_names[0], (int) Value, Value);
}
if (values_.Count > 0) {
output.WriteEnumArray(2, field_names[1], values_);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
return CalcSerializedSize();
}
}
private int CalcSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (hasValue) {
size += pb::CodedOutputStream.ComputeEnumSize(1, (int) Value);
}
{
int dataSize = 0;
if (values_.Count > 0) {
foreach (global::Google.ProtocolBuffers.TestProtos.DownRevision.Types.Enum element in values_) {
dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag((int) element);
}
size += dataSize;
size += 1 * values_.Count;
}
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
public static DownRevision ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static DownRevision ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static DownRevision ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static DownRevision ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static DownRevision ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static DownRevision ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static DownRevision ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static DownRevision ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static DownRevision ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static DownRevision ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private DownRevision MakeReadOnly() {
values_.MakeReadOnly();
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(DownRevision prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<DownRevision, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(DownRevision cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private DownRevision result;
private DownRevision PrepareBuilder() {
if (resultIsReadOnly) {
DownRevision original = result;
result = new DownRevision();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override DownRevision MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::Google.ProtocolBuffers.TestProtos.DownRevision.Descriptor; }
}
public override DownRevision DefaultInstanceForType {
get { return global::Google.ProtocolBuffers.TestProtos.DownRevision.DefaultInstance; }
}
public override DownRevision BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is DownRevision) {
return MergeFrom((DownRevision) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(DownRevision other) {
if (other == global::Google.ProtocolBuffers.TestProtos.DownRevision.DefaultInstance) return this;
PrepareBuilder();
if (other.HasValue) {
Value = other.Value;
}
if (other.values_.Count != 0) {
result.values_.Add(other.values_);
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_downRevisionFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _downRevisionFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 8: {
object unknown;
if(input.ReadEnum(ref result.value_, out unknown)) {
result.hasValue = true;
} else if(unknown is int) {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
unknownFields.MergeVarintField(1, (ulong)(int)unknown);
}
break;
}
case 18:
case 16: {
scg::ICollection<object> unknownItems;
input.ReadEnumArray<global::Google.ProtocolBuffers.TestProtos.DownRevision.Types.Enum>(tag, field_name, result.values_, out unknownItems);
if (unknownItems != null) {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
foreach (object rawValue in unknownItems)
if (rawValue is int)
unknownFields.MergeVarintField(2, (ulong)(int)rawValue);
}
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public bool HasValue {
get { return result.hasValue; }
}
public global::Google.ProtocolBuffers.TestProtos.DownRevision.Types.Enum Value {
get { return result.Value; }
set { SetValue(value); }
}
public Builder SetValue(global::Google.ProtocolBuffers.TestProtos.DownRevision.Types.Enum value) {
PrepareBuilder();
result.hasValue = true;
result.value_ = value;
return this;
}
public Builder ClearValue() {
PrepareBuilder();
result.hasValue = false;
result.value_ = global::Google.ProtocolBuffers.TestProtos.DownRevision.Types.Enum.DEFAULT_VALUE;
return this;
}
public pbc::IPopsicleList<global::Google.ProtocolBuffers.TestProtos.DownRevision.Types.Enum> ValuesList {
get { return PrepareBuilder().values_; }
}
public int ValuesCount {
get { return result.ValuesCount; }
}
public global::Google.ProtocolBuffers.TestProtos.DownRevision.Types.Enum GetValues(int index) {
return result.GetValues(index);
}
public Builder SetValues(int index, global::Google.ProtocolBuffers.TestProtos.DownRevision.Types.Enum value) {
PrepareBuilder();
result.values_[index] = value;
return this;
}
public Builder AddValues(global::Google.ProtocolBuffers.TestProtos.DownRevision.Types.Enum value) {
PrepareBuilder();
result.values_.Add(value);
return this;
}
public Builder AddRangeValues(scg::IEnumerable<global::Google.ProtocolBuffers.TestProtos.DownRevision.Types.Enum> values) {
PrepareBuilder();
result.values_.Add(values);
return this;
}
public Builder ClearValues() {
PrepareBuilder();
result.values_.Clear();
return this;
}
}
static DownRevision() {
object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.UnknownEnumTest.Descriptor, null);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class UpRevision : pb::GeneratedMessage<UpRevision, UpRevision.Builder> {
private UpRevision() { }
private static readonly UpRevision defaultInstance = new UpRevision().MakeReadOnly();
private static readonly string[] _upRevisionFieldNames = new string[] { "value", "values" };
private static readonly uint[] _upRevisionFieldTags = new uint[] { 8, 16 };
public static UpRevision DefaultInstance {
get { return defaultInstance; }
}
public override UpRevision DefaultInstanceForType {
get { return DefaultInstance; }
}
protected override UpRevision ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::Google.ProtocolBuffers.TestProtos.UnknownEnumTest.internal__static_google_protobuf_util_UpRevision__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<UpRevision, UpRevision.Builder> InternalFieldAccessors {
get { return global::Google.ProtocolBuffers.TestProtos.UnknownEnumTest.internal__static_google_protobuf_util_UpRevision__FieldAccessorTable; }
}
#region Nested types
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class Types {
public enum Enum {
DEFAULT_VALUE = 2,
NONDEFAULT_VALUE = 3,
NEW_VALUE = 4,
NEW_VALUE_2 = 5,
NEW_VALUE_3 = 6,
}
}
#endregion
public const int ValueFieldNumber = 1;
private bool hasValue;
private global::Google.ProtocolBuffers.TestProtos.UpRevision.Types.Enum value_ = global::Google.ProtocolBuffers.TestProtos.UpRevision.Types.Enum.DEFAULT_VALUE;
public bool HasValue {
get { return hasValue; }
}
public global::Google.ProtocolBuffers.TestProtos.UpRevision.Types.Enum Value {
get { return value_; }
}
public const int ValuesFieldNumber = 2;
private pbc::PopsicleList<global::Google.ProtocolBuffers.TestProtos.UpRevision.Types.Enum> values_ = new pbc::PopsicleList<global::Google.ProtocolBuffers.TestProtos.UpRevision.Types.Enum>();
public scg::IList<global::Google.ProtocolBuffers.TestProtos.UpRevision.Types.Enum> ValuesList {
get { return pbc::Lists.AsReadOnly(values_); }
}
public int ValuesCount {
get { return values_.Count; }
}
public global::Google.ProtocolBuffers.TestProtos.UpRevision.Types.Enum GetValues(int index) {
return values_[index];
}
public override bool IsInitialized {
get {
return true;
}
}
public override void WriteTo(pb::ICodedOutputStream output) {
CalcSerializedSize();
string[] field_names = _upRevisionFieldNames;
if (hasValue) {
output.WriteEnum(1, field_names[0], (int) Value, Value);
}
if (values_.Count > 0) {
output.WriteEnumArray(2, field_names[1], values_);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
return CalcSerializedSize();
}
}
private int CalcSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (hasValue) {
size += pb::CodedOutputStream.ComputeEnumSize(1, (int) Value);
}
{
int dataSize = 0;
if (values_.Count > 0) {
foreach (global::Google.ProtocolBuffers.TestProtos.UpRevision.Types.Enum element in values_) {
dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag((int) element);
}
size += dataSize;
size += 1 * values_.Count;
}
}
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
public static UpRevision ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static UpRevision ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static UpRevision ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static UpRevision ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static UpRevision ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static UpRevision ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static UpRevision ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static UpRevision ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static UpRevision ParseFrom(pb::ICodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static UpRevision ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
private UpRevision MakeReadOnly() {
values_.MakeReadOnly();
return this;
}
public static Builder CreateBuilder() { return new Builder(); }
public override Builder ToBuilder() { return CreateBuilder(this); }
public override Builder CreateBuilderForType() { return new Builder(); }
public static Builder CreateBuilder(UpRevision prototype) {
return new Builder(prototype);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class Builder : pb::GeneratedBuilder<UpRevision, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {
result = DefaultInstance;
resultIsReadOnly = true;
}
internal Builder(UpRevision cloneFrom) {
result = cloneFrom;
resultIsReadOnly = true;
}
private bool resultIsReadOnly;
private UpRevision result;
private UpRevision PrepareBuilder() {
if (resultIsReadOnly) {
UpRevision original = result;
result = new UpRevision();
resultIsReadOnly = false;
MergeFrom(original);
}
return result;
}
public override bool IsInitialized {
get { return result.IsInitialized; }
}
protected override UpRevision MessageBeingBuilt {
get { return PrepareBuilder(); }
}
public override Builder Clear() {
result = DefaultInstance;
resultIsReadOnly = true;
return this;
}
public override Builder Clone() {
if (resultIsReadOnly) {
return new Builder(result);
} else {
return new Builder().MergeFrom(result);
}
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::Google.ProtocolBuffers.TestProtos.UpRevision.Descriptor; }
}
public override UpRevision DefaultInstanceForType {
get { return global::Google.ProtocolBuffers.TestProtos.UpRevision.DefaultInstance; }
}
public override UpRevision BuildPartial() {
if (resultIsReadOnly) {
return result;
}
resultIsReadOnly = true;
return result.MakeReadOnly();
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is UpRevision) {
return MergeFrom((UpRevision) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(UpRevision other) {
if (other == global::Google.ProtocolBuffers.TestProtos.UpRevision.DefaultInstance) return this;
PrepareBuilder();
if (other.HasValue) {
Value = other.Value;
}
if (other.values_.Count != 0) {
result.values_.Add(other.values_);
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::ICodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
PrepareBuilder();
pb::UnknownFieldSet.Builder unknownFields = null;
uint tag;
string field_name;
while (input.ReadTag(out tag, out field_name)) {
if(tag == 0 && field_name != null) {
int field_ordinal = global::System.Array.BinarySearch(_upRevisionFieldNames, field_name, global::System.StringComparer.Ordinal);
if(field_ordinal >= 0)
tag = _upRevisionFieldTags[field_ordinal];
else {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
continue;
}
}
switch (tag) {
case 0: {
throw pb::InvalidProtocolBufferException.InvalidTag();
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name);
break;
}
case 8: {
object unknown;
if(input.ReadEnum(ref result.value_, out unknown)) {
result.hasValue = true;
} else if(unknown is int) {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
unknownFields.MergeVarintField(1, (ulong)(int)unknown);
}
break;
}
case 18:
case 16: {
scg::ICollection<object> unknownItems;
input.ReadEnumArray<global::Google.ProtocolBuffers.TestProtos.UpRevision.Types.Enum>(tag, field_name, result.values_, out unknownItems);
if (unknownItems != null) {
if (unknownFields == null) {
unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);
}
foreach (object rawValue in unknownItems)
if (rawValue is int)
unknownFields.MergeVarintField(2, (ulong)(int)rawValue);
}
break;
}
}
}
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
public bool HasValue {
get { return result.hasValue; }
}
public global::Google.ProtocolBuffers.TestProtos.UpRevision.Types.Enum Value {
get { return result.Value; }
set { SetValue(value); }
}
public Builder SetValue(global::Google.ProtocolBuffers.TestProtos.UpRevision.Types.Enum value) {
PrepareBuilder();
result.hasValue = true;
result.value_ = value;
return this;
}
public Builder ClearValue() {
PrepareBuilder();
result.hasValue = false;
result.value_ = global::Google.ProtocolBuffers.TestProtos.UpRevision.Types.Enum.DEFAULT_VALUE;
return this;
}
public pbc::IPopsicleList<global::Google.ProtocolBuffers.TestProtos.UpRevision.Types.Enum> ValuesList {
get { return PrepareBuilder().values_; }
}
public int ValuesCount {
get { return result.ValuesCount; }
}
public global::Google.ProtocolBuffers.TestProtos.UpRevision.Types.Enum GetValues(int index) {
return result.GetValues(index);
}
public Builder SetValues(int index, global::Google.ProtocolBuffers.TestProtos.UpRevision.Types.Enum value) {
PrepareBuilder();
result.values_[index] = value;
return this;
}
public Builder AddValues(global::Google.ProtocolBuffers.TestProtos.UpRevision.Types.Enum value) {
PrepareBuilder();
result.values_.Add(value);
return this;
}
public Builder AddRangeValues(scg::IEnumerable<global::Google.ProtocolBuffers.TestProtos.UpRevision.Types.Enum> values) {
PrepareBuilder();
result.values_.Add(values);
return this;
}
public Builder ClearValues() {
PrepareBuilder();
result.values_.Clear();
return this;
}
}
static UpRevision() {
object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.UnknownEnumTest.Descriptor, null);
}
}
#endregion
}
#endregion Designer generated code

@ -1,83 +0,0 @@
using System;
using System.IO;
using System.Text;
using Google.ProtocolBuffers.TestProtos;
using Google.ProtocolBuffers.Serialization.Http;
using NUnit.Framework;
namespace Google.ProtocolBuffers
{
public class TestReaderForUrlEncoded
{
[Test]
public void Example_FromQueryString()
{
Uri sampleUri = new Uri("http://sample.com/Path/File.ext?text=two+three%20four&valid=true&numbers=1&numbers=2", UriKind.Absolute);
ICodedInputStream input = FormUrlEncodedReader.CreateInstance(sampleUri.Query);
TestXmlMessage.Builder builder = TestXmlMessage.CreateBuilder();
builder.MergeFrom(input);
TestXmlMessage message = builder.Build();
Assert.AreEqual(true, message.Valid);
Assert.AreEqual("two three four", message.Text);
Assert.AreEqual(2, message.NumbersCount);
Assert.AreEqual(1, message.NumbersList[0]);
Assert.AreEqual(2, message.NumbersList[1]);
}
[Test]
public void Example_FromFormData()
{
Stream rawPost = new MemoryStream(Encoding.UTF8.GetBytes("text=two+three%20four&valid=true&numbers=1&numbers=2"), false);
ICodedInputStream input = FormUrlEncodedReader.CreateInstance(rawPost);
TestXmlMessage.Builder builder = TestXmlMessage.CreateBuilder();
builder.MergeFrom(input);
TestXmlMessage message = builder.Build();
Assert.AreEqual(true, message.Valid);
Assert.AreEqual("two three four", message.Text);
Assert.AreEqual(2, message.NumbersCount);
Assert.AreEqual(1, message.NumbersList[0]);
Assert.AreEqual(2, message.NumbersList[1]);
}
[Test]
public void TestEmptyValues()
{
ICodedInputStream input = FormUrlEncodedReader.CreateInstance("valid=true&text=&numbers=1");
TestXmlMessage.Builder builder = TestXmlMessage.CreateBuilder();
builder.MergeFrom(input);
Assert.IsTrue(builder.Valid);
Assert.IsTrue(builder.HasText);
Assert.AreEqual("", builder.Text);
Assert.AreEqual(1, builder.NumbersCount);
Assert.AreEqual(1, builder.NumbersList[0]);
}
[Test]
public void TestNoValue()
{
ICodedInputStream input = FormUrlEncodedReader.CreateInstance("valid=true&text&numbers=1");
TestXmlMessage.Builder builder = TestXmlMessage.CreateBuilder();
builder.MergeFrom(input);
Assert.IsTrue(builder.Valid);
Assert.IsTrue(builder.HasText);
Assert.AreEqual("", builder.Text);
Assert.AreEqual(1, builder.NumbersCount);
Assert.AreEqual(1, builder.NumbersList[0]);
}
[Test]
public void FormUrlEncodedReaderDoesNotSupportChildren()
{
ICodedInputStream input = FormUrlEncodedReader.CreateInstance("child=uh0");
Assert.Throws<NotSupportedException>(() => TestXmlMessage.CreateBuilder().MergeFrom(input));
}
}
}

@ -1,301 +0,0 @@
namespace Google.ProtocolBuffers
{
internal class TestResources
{
#region golden_message
internal static byte[] golden_message
{
get
{
return System.Convert.FromBase64String(@"
CGUQZhhnIGgo0gEw1AE9awAAAEFsAAAAAAAAAE1tAAAAUW4AAAAAAAAAXQAA3kJhAAAAAAAAXEBo
AXIDMTE1egMxMTaDAYgBdYQBkgECCHaaAQIId6IBAgh4qAEDsAEGuAEJwgEDMTI0ygEDMTI1+AHJ
AfgBrQKAAsoBgAKuAogCywGIAq8CkALMAZACsAKYApoDmALiBKACnAOgAuQErQLPAAAArQIzAQAA
sQLQAAAAAAAAALECNAEAAAAAAAC9AtEAAAC9AjUBAADBAtIAAAAAAAAAwQI2AQAAAAAAAM0CAABT
Q80CAICbQ9ECAAAAAACAakDRAgAAAAAAgHNA2AIB2AIA4gIDMjE14gIDMzE16gIDMjE26gIDMzE2
8wL4AtkB9ALzAvgCvQL0AoIDAwjaAYIDAwi+AooDAwjbAYoDAwi/ApIDAwjcAZIDAwjAApgDApgD
A6ADBaADBqgDCKgDCbIDAzIyNLIDAzMyNLoDAzIyNboDAzMyNegDkQPwA5ID+AOTA4AElAOIBKoG
kASsBp0ElwEAAKEEmAEAAAAAAACtBJkBAACxBJoBAAAAAAAAvQQAgM1DwQQAAAAAAMB5QMgEANIE
AzQxNdoEAzQxNogFAZAFBJgFB6IFAzQyNKoFAzQyNZIHAzYwNA==
");
}
}
#endregion
#region golden_packed_fields_message
internal static byte[] golden_packed_fields_message
{
get
{
return System.Convert.FromBase64String(@"
0gUE2QS9BdoFBNoEvgXiBQTbBL8F6gUE3ATABfIFBLoJggv6BQS8CYQLggYIXwIAAMMCAACKBhBg
AgAAAAAAAMQCAAAAAAAAkgYIYQIAAMUCAACaBhBiAgAAAAAAAMYCAAAAAAAAogYIAMAYRADAMUSq
BhAAAAAAACCDQAAAAAAAQIZAsgYCAQC6BgIFBg==
");
}
}
#endregion
#region text_format_unittest_data
internal static string text_format_unittest_data
{
get
{
return @"
optional_int32: 101
optional_int64: 102
optional_uint32: 103
optional_uint64: 104
optional_sint32: 105
optional_sint64: 106
optional_fixed32: 107
optional_fixed64: 108
optional_sfixed32: 109
optional_sfixed64: 110
optional_float: 111
optional_double: 112
optional_bool: true
optional_string: ""115""
optional_bytes: ""116""
OptionalGroup {
a: 117
}
optional_nested_message {
bb: 118
}
optional_foreign_message {
c: 119
}
optional_import_message {
d: 120
}
optional_nested_enum: BAZ
optional_foreign_enum: FOREIGN_BAZ
optional_import_enum: IMPORT_BAZ
optional_string_piece: ""124""
optional_cord: ""125""
repeated_int32: 201
repeated_int32: 301
repeated_int64: 202
repeated_int64: 302
repeated_uint32: 203
repeated_uint32: 303
repeated_uint64: 204
repeated_uint64: 304
repeated_sint32: 205
repeated_sint32: 305
repeated_sint64: 206
repeated_sint64: 306
repeated_fixed32: 207
repeated_fixed32: 307
repeated_fixed64: 208
repeated_fixed64: 308
repeated_sfixed32: 209
repeated_sfixed32: 309
repeated_sfixed64: 210
repeated_sfixed64: 310
repeated_float: 211
repeated_float: 311
repeated_double: 212
repeated_double: 312
repeated_bool: true
repeated_bool: false
repeated_string: ""215""
repeated_string: ""315""
repeated_bytes: ""216""
repeated_bytes: ""316""
RepeatedGroup {
a: 217
}
RepeatedGroup {
a: 317
}
repeated_nested_message {
bb: 218
}
repeated_nested_message {
bb: 318
}
repeated_foreign_message {
c: 219
}
repeated_foreign_message {
c: 319
}
repeated_import_message {
d: 220
}
repeated_import_message {
d: 320
}
repeated_nested_enum: BAR
repeated_nested_enum: BAZ
repeated_foreign_enum: FOREIGN_BAR
repeated_foreign_enum: FOREIGN_BAZ
repeated_import_enum: IMPORT_BAR
repeated_import_enum: IMPORT_BAZ
repeated_string_piece: ""224""
repeated_string_piece: ""324""
repeated_cord: ""225""
repeated_cord: ""325""
default_int32: 401
default_int64: 402
default_uint32: 403
default_uint64: 404
default_sint32: 405
default_sint64: 406
default_fixed32: 407
default_fixed64: 408
default_sfixed32: 409
default_sfixed64: 410
default_float: 411
default_double: 412
default_bool: false
default_string: ""415""
default_bytes: ""416""
default_nested_enum: FOO
default_foreign_enum: FOREIGN_FOO
default_import_enum: IMPORT_FOO
default_string_piece: ""424""
default_cord: ""425""
oneof_bytes: ""604""
";
}
}
#endregion
#region text_format_unittest_extensions_data
internal static string text_format_unittest_extensions_data
{
get
{
return @"
[protobuf_unittest.optional_int32_extension]: 101
[protobuf_unittest.optional_int64_extension]: 102
[protobuf_unittest.optional_uint32_extension]: 103
[protobuf_unittest.optional_uint64_extension]: 104
[protobuf_unittest.optional_sint32_extension]: 105
[protobuf_unittest.optional_sint64_extension]: 106
[protobuf_unittest.optional_fixed32_extension]: 107
[protobuf_unittest.optional_fixed64_extension]: 108
[protobuf_unittest.optional_sfixed32_extension]: 109
[protobuf_unittest.optional_sfixed64_extension]: 110
[protobuf_unittest.optional_float_extension]: 111
[protobuf_unittest.optional_double_extension]: 112
[protobuf_unittest.optional_bool_extension]: true
[protobuf_unittest.optional_string_extension]: ""115""
[protobuf_unittest.optional_bytes_extension]: ""116""
[protobuf_unittest.optionalgroup_extension] {
a: 117
}
[protobuf_unittest.optional_nested_message_extension] {
bb: 118
}
[protobuf_unittest.optional_foreign_message_extension] {
c: 119
}
[protobuf_unittest.optional_import_message_extension] {
d: 120
}
[protobuf_unittest.optional_nested_enum_extension]: BAZ
[protobuf_unittest.optional_foreign_enum_extension]: FOREIGN_BAZ
[protobuf_unittest.optional_import_enum_extension]: IMPORT_BAZ
[protobuf_unittest.optional_string_piece_extension]: ""124""
[protobuf_unittest.optional_cord_extension]: ""125""
[protobuf_unittest.repeated_int32_extension]: 201
[protobuf_unittest.repeated_int32_extension]: 301
[protobuf_unittest.repeated_int64_extension]: 202
[protobuf_unittest.repeated_int64_extension]: 302
[protobuf_unittest.repeated_uint32_extension]: 203
[protobuf_unittest.repeated_uint32_extension]: 303
[protobuf_unittest.repeated_uint64_extension]: 204
[protobuf_unittest.repeated_uint64_extension]: 304
[protobuf_unittest.repeated_sint32_extension]: 205
[protobuf_unittest.repeated_sint32_extension]: 305
[protobuf_unittest.repeated_sint64_extension]: 206
[protobuf_unittest.repeated_sint64_extension]: 306
[protobuf_unittest.repeated_fixed32_extension]: 207
[protobuf_unittest.repeated_fixed32_extension]: 307
[protobuf_unittest.repeated_fixed64_extension]: 208
[protobuf_unittest.repeated_fixed64_extension]: 308
[protobuf_unittest.repeated_sfixed32_extension]: 209
[protobuf_unittest.repeated_sfixed32_extension]: 309
[protobuf_unittest.repeated_sfixed64_extension]: 210
[protobuf_unittest.repeated_sfixed64_extension]: 310
[protobuf_unittest.repeated_float_extension]: 211
[protobuf_unittest.repeated_float_extension]: 311
[protobuf_unittest.repeated_double_extension]: 212
[protobuf_unittest.repeated_double_extension]: 312
[protobuf_unittest.repeated_bool_extension]: true
[protobuf_unittest.repeated_bool_extension]: false
[protobuf_unittest.repeated_string_extension]: ""215""
[protobuf_unittest.repeated_string_extension]: ""315""
[protobuf_unittest.repeated_bytes_extension]: ""216""
[protobuf_unittest.repeated_bytes_extension]: ""316""
[protobuf_unittest.repeatedgroup_extension] {
a: 217
}
[protobuf_unittest.repeatedgroup_extension] {
a: 317
}
[protobuf_unittest.repeated_nested_message_extension] {
bb: 218
}
[protobuf_unittest.repeated_nested_message_extension] {
bb: 318
}
[protobuf_unittest.repeated_foreign_message_extension] {
c: 219
}
[protobuf_unittest.repeated_foreign_message_extension] {
c: 319
}
[protobuf_unittest.repeated_import_message_extension] {
d: 220
}
[protobuf_unittest.repeated_import_message_extension] {
d: 320
}
[protobuf_unittest.repeated_nested_enum_extension]: BAR
[protobuf_unittest.repeated_nested_enum_extension]: BAZ
[protobuf_unittest.repeated_foreign_enum_extension]: FOREIGN_BAR
[protobuf_unittest.repeated_foreign_enum_extension]: FOREIGN_BAZ
[protobuf_unittest.repeated_import_enum_extension]: IMPORT_BAR
[protobuf_unittest.repeated_import_enum_extension]: IMPORT_BAZ
[protobuf_unittest.repeated_string_piece_extension]: ""224""
[protobuf_unittest.repeated_string_piece_extension]: ""324""
[protobuf_unittest.repeated_cord_extension]: ""225""
[protobuf_unittest.repeated_cord_extension]: ""325""
[protobuf_unittest.default_int32_extension]: 401
[protobuf_unittest.default_int64_extension]: 402
[protobuf_unittest.default_uint32_extension]: 403
[protobuf_unittest.default_uint64_extension]: 404
[protobuf_unittest.default_sint32_extension]: 405
[protobuf_unittest.default_sint64_extension]: 406
[protobuf_unittest.default_fixed32_extension]: 407
[protobuf_unittest.default_fixed64_extension]: 408
[protobuf_unittest.default_sfixed32_extension]: 409
[protobuf_unittest.default_sfixed64_extension]: 410
[protobuf_unittest.default_float_extension]: 411
[protobuf_unittest.default_double_extension]: 412
[protobuf_unittest.default_bool_extension]: false
[protobuf_unittest.default_string_extension]: ""415""
[protobuf_unittest.default_bytes_extension]: ""416""
[protobuf_unittest.default_nested_enum_extension]: FOO
[protobuf_unittest.default_foreign_enum_extension]: FOREIGN_FOO
[protobuf_unittest.default_import_enum_extension]: IMPORT_FOO
[protobuf_unittest.default_string_piece_extension]: ""424""
[protobuf_unittest.default_cord_extension]: ""425""
[protobuf_unittest.oneof_uint32_extension]: 601
[protobuf_unittest.oneof_nested_message_extension] {
bb: 602
}
[protobuf_unittest.oneof_string_extension]: ""603""
[protobuf_unittest.oneof_bytes_extension]: ""604""
";
}
}
#endregion
}
}

File diff suppressed because it is too large Load Diff

@ -1,498 +0,0 @@
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using EnumOptions = Google.ProtocolBuffers.TestProtos.EnumOptions;
using Google.ProtocolBuffers.DescriptorProtos;
using Google.ProtocolBuffers.Serialization;
using Google.ProtocolBuffers.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers
{
public class TestWriterFormatJson
{
[Test]
public void Example_FromJson()
{
TestXmlMessage.Builder builder = TestXmlMessage.CreateBuilder();
//3.5: builder.MergeFromJson(@"{""valid"":true}");
Extensions.MergeFromJson(builder, @"{""valid"":true}");
TestXmlMessage message = builder.Build();
Assert.AreEqual(true, message.Valid);
}
[Test]
public void Example_ToJson()
{
TestXmlMessage message =
TestXmlMessage.CreateBuilder()
.SetValid(true)
.Build();
//3.5: string json = message.ToJson();
string json = Extensions.ToJson(message);
Assert.AreEqual(@"{""valid"":true}", json);
}
[Test]
public void Example_WriteJsonUsingICodedOutputStream()
{
TestXmlMessage message =
TestXmlMessage.CreateBuilder()
.SetValid(true)
.Build();
using (TextWriter output = new StringWriter())
{
ICodedOutputStream writer = JsonFormatWriter.CreateInstance(output);
writer.WriteMessageStart(); //manually begin the message, output is '{'
writer.Flush();
Assert.AreEqual("{", output.ToString());
ICodedOutputStream stream = writer;
message.WriteTo(stream); //write the message normally
writer.Flush();
Assert.AreEqual(@"{""valid"":true", output.ToString());
writer.WriteMessageEnd(); //manually write the end message '}'
Assert.AreEqual(@"{""valid"":true}", output.ToString());
}
}
[Test]
public void Example_ReadJsonUsingICodedInputStream()
{
TestXmlMessage.Builder builder = TestXmlMessage.CreateBuilder();
ICodedInputStream reader = JsonFormatReader.CreateInstance(@"{""valid"":true}");
reader.ReadMessageStart(); //manually read the begin the message '{'
builder.MergeFrom(reader); //write the message normally
reader.ReadMessageEnd(); //manually read the end message '}'
}
protected string Content;
[System.Diagnostics.DebuggerNonUserCode]
protected void FormatterAssert<TMessage>(TMessage message, params string[] expecting) where TMessage : IMessageLite
{
StringWriter sw = new StringWriter();
JsonFormatWriter.CreateInstance(sw).WriteMessage(message);
Content = sw.ToString();
ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
UnittestExtrasXmltest.RegisterAllExtensions(registry);
IMessageLite copy =
JsonFormatReader.CreateInstance(Content)
.Merge(message.WeakCreateBuilderForType(), registry).WeakBuild();
Assert.AreEqual(typeof(TMessage), copy.GetType());
Assert.AreEqual(message, copy);
foreach (string expect in expecting)
{
Assert.IsTrue(Content.IndexOf(expect) >= 0);
}
}
[Test]
public void TestToJsonParseFromJson()
{
TestAllTypes msg = new TestAllTypes.Builder().SetDefaultBool(true).Build();
string json = Extensions.ToJson(msg);
Assert.AreEqual("{\"default_bool\":true}", json);
TestAllTypes copy = Extensions.MergeFromJson(new TestAllTypes.Builder(), json).Build();
Assert.IsTrue(copy.HasDefaultBool && copy.DefaultBool);
Assert.AreEqual(msg, copy);
}
[Test]
public void TestToJsonParseFromJsonReader()
{
TestAllTypes msg = new TestAllTypes.Builder().SetDefaultBool(true).Build();
string json = Extensions.ToJson(msg);
Assert.AreEqual("{\"default_bool\":true}", json);
TestAllTypes copy = Extensions.MergeFromJson(new TestAllTypes.Builder(), new StringReader(json)).Build();
Assert.IsTrue(copy.HasDefaultBool && copy.DefaultBool);
Assert.AreEqual(msg, copy);
}
[Test]
public void TestJsonFormatted()
{
TestXmlMessage message = TestXmlMessage.CreateBuilder()
.SetValid(true)
.SetNumber(0x1010)
.AddChildren(TestXmlMessage.Types.Children.CreateBuilder())
.AddChildren(TestXmlMessage.Types.Children.CreateBuilder().AddOptions(EnumOptions.ONE))
.AddChildren(TestXmlMessage.Types.Children.CreateBuilder().AddOptions(EnumOptions.ONE).AddOptions(EnumOptions.TWO))
.AddChildren(TestXmlMessage.Types.Children.CreateBuilder().SetBinary(ByteString.CopyFromUtf8("abc")))
.Build();
StringWriter sw = new StringWriter();
JsonFormatWriter.CreateInstance(sw).Formatted()
.WriteMessage(message);
string json = sw.ToString();
TestXmlMessage copy = JsonFormatReader.CreateInstance(json)
.Merge(TestXmlMessage.CreateBuilder()).Build();
Assert.AreEqual(message, copy);
}
[Test]
public void TestEmptyMessage()
{
FormatterAssert(
TestXmlChild.CreateBuilder()
.Build(),
@"{}"
);
}
[Test]
public void TestRepeatedField()
{
FormatterAssert(
TestXmlChild.CreateBuilder()
.AddOptions(EnumOptions.ONE)
.AddOptions(EnumOptions.TWO)
.Build(),
@"{""options"":[""ONE"",""TWO""]}"
);
}
[Test]
public void TestNestedEmptyMessage()
{
FormatterAssert(
TestXmlMessage.CreateBuilder()
.SetChild(TestXmlChild.CreateBuilder().Build())
.Build(),
@"{""child"":{}}"
);
}
[Test]
public void TestNestedMessage()
{
FormatterAssert(
TestXmlMessage.CreateBuilder()
.SetChild(TestXmlChild.CreateBuilder().AddOptions(EnumOptions.TWO).Build())
.Build(),
@"{""child"":{""options"":[""TWO""]}}"
);
}
[Test]
public void TestBooleanTypes()
{
FormatterAssert(
TestXmlMessage.CreateBuilder()
.SetValid(true)
.Build(),
@"{""valid"":true}"
);
}
[Test]
public void TestFullMessage()
{
FormatterAssert(
TestXmlMessage.CreateBuilder()
.SetValid(true)
.SetText("text")
.AddTextlines("a")
.AddTextlines("b")
.AddTextlines("c")
.SetNumber(0x1010101010)
.AddNumbers(1)
.AddNumbers(2)
.AddNumbers(3)
.SetChild(TestXmlChild.CreateBuilder().AddOptions(EnumOptions.ONE).SetBinary(ByteString.CopyFrom(new byte[1])))
.AddChildren(TestXmlMessage.Types.Children.CreateBuilder().AddOptions(EnumOptions.TWO).SetBinary(ByteString.CopyFrom(new byte[2])))
.AddChildren(TestXmlMessage.Types.Children.CreateBuilder().AddOptions(EnumOptions.THREE).SetBinary(ByteString.CopyFrom(new byte[3])))
.Build(),
@"""text"":""text""",
@"[""a"",""b"",""c""]",
@"[1,2,3]",
@"""child"":{",
@"""children"":[{",
@"AA==",
@"AAA=",
@"AAAA",
0x1010101010L.ToString()
);
}
[Test]
public void TestMessageWithXmlText()
{
FormatterAssert(
TestXmlMessage.CreateBuilder()
.SetText("<text></text>")
.Build(),
@"{""text"":""<text><\/text>""}"
);
}
[Test]
public void TestWithEscapeChars()
{
FormatterAssert(
TestXmlMessage.CreateBuilder()
.SetText(" \t <- \"leading space and trailing\" -> \\ \xef54 \x0000 \xFF \xFFFF \b \f \r \n \t ")
.Build(),
"{\"text\":\" \\t <- \\\"leading space and trailing\\\" -> \\\\ \\uef54 \\u0000 \\u00ff \\uffff \\b \\f \\r \\n \\t \"}"
);
}
[Test]
public void TestWithExtensionText()
{
FormatterAssert(
TestXmlMessage.CreateBuilder()
.SetValid(false)
.SetExtension(UnittestExtrasXmltest.ExtensionText, " extension text value ! ")
.Build(),
@"{""valid"":false,""extension_text"":"" extension text value ! ""}"
);
}
[Test]
public void TestWithExtensionNumber()
{
FormatterAssert(
TestXmlMessage.CreateBuilder()
.SetExtension(UnittestExtrasXmltest.ExtensionMessage,
new TestXmlExtension.Builder().SetNumber(42).Build())
.Build(),
@"{""number"":42}"
);
}
[Test]
public void TestWithExtensionArray()
{
FormatterAssert(
TestXmlMessage.CreateBuilder()
.AddExtension(UnittestExtrasXmltest.ExtensionNumber, 100)
.AddExtension(UnittestExtrasXmltest.ExtensionNumber, 101)
.AddExtension(UnittestExtrasXmltest.ExtensionNumber, 102)
.Build(),
@"{""extension_number"":[100,101,102]}"
);
}
[Test]
public void TestWithExtensionEnum()
{
FormatterAssert(
TestXmlMessage.CreateBuilder()
.SetExtension(UnittestExtrasXmltest.ExtensionEnum, EnumOptions.ONE)
.Build(),
@"{""extension_enum"":""ONE""}"
);
}
[Test]
public void TestMessageWithExtensions()
{
FormatterAssert(
TestXmlMessage.CreateBuilder()
.SetValid(true)
.SetText("text")
.SetExtension(UnittestExtrasXmltest.ExtensionText, "extension text")
.SetExtension(UnittestExtrasXmltest.ExtensionMessage, new TestXmlExtension.Builder().SetNumber(42).Build())
.AddExtension(UnittestExtrasXmltest.ExtensionNumber, 100)
.AddExtension(UnittestExtrasXmltest.ExtensionNumber, 101)
.AddExtension(UnittestExtrasXmltest.ExtensionNumber, 102)
.SetExtension(UnittestExtrasXmltest.ExtensionEnum, EnumOptions.ONE)
.Build(),
@"""text"":""text""",
@"""valid"":true",
@"""extension_enum"":""ONE""",
@"""extension_text"":""extension text""",
@"""extension_number"":[100,101,102]",
@"""extension_message"":{""number"":42}"
);
}
[Test]
public void TestMessageMissingExtensions()
{
TestXmlMessage original = TestXmlMessage.CreateBuilder()
.SetValid(true)
.SetText("text")
.SetExtension(UnittestExtrasXmltest.ExtensionText, " extension text value ! ")
.SetExtension(UnittestExtrasXmltest.ExtensionMessage, new TestXmlExtension.Builder().SetNumber(42).Build())
.AddExtension(UnittestExtrasXmltest.ExtensionNumber, 100)
.AddExtension(UnittestExtrasXmltest.ExtensionNumber, 101)
.AddExtension(UnittestExtrasXmltest.ExtensionNumber, 102)
.SetExtension(UnittestExtrasXmltest.ExtensionEnum, EnumOptions.ONE)
.Build();
TestXmlMessage message = original.ToBuilder()
.ClearExtension(UnittestExtrasXmltest.ExtensionText)
.ClearExtension(UnittestExtrasXmltest.ExtensionMessage)
.ClearExtension(UnittestExtrasXmltest.ExtensionNumber)
.ClearExtension(UnittestExtrasXmltest.ExtensionEnum)
.Build();
JsonFormatWriter writer = JsonFormatWriter.CreateInstance();
writer.WriteMessage(original);
Content = writer.ToString();
IMessageLite copy = JsonFormatReader.CreateInstance(Content)
.Merge(message.CreateBuilderForType()).Build();
Assert.AreNotEqual(original, message);
Assert.AreNotEqual(original, copy);
Assert.AreEqual(message, copy);
}
[Test]
public void TestMergeFields()
{
TestXmlMessage.Builder builder = TestXmlMessage.CreateBuilder();
builder.MergeFrom(JsonFormatReader.CreateInstance("\"valid\": true"));
builder.MergeFrom(JsonFormatReader.CreateInstance("\"text\": \"text\", \"number\": \"411\""));
Assert.AreEqual(true, builder.Valid);
Assert.AreEqual("text", builder.Text);
Assert.AreEqual(411, builder.Number);
}
[Test]
public void TestMessageArray()
{
JsonFormatWriter writer = JsonFormatWriter.CreateInstance().Formatted();
using (writer.StartArray())
{
writer.WriteMessage(TestXmlMessage.CreateBuilder().SetNumber(1).AddTextlines("a").Build());
writer.WriteMessage(TestXmlMessage.CreateBuilder().SetNumber(2).AddTextlines("b").Build());
writer.WriteMessage(TestXmlMessage.CreateBuilder().SetNumber(3).AddTextlines("c").Build());
}
string json = writer.ToString();
JsonFormatReader reader = JsonFormatReader.CreateInstance(json);
TestXmlMessage.Builder builder = TestXmlMessage.CreateBuilder();
int ordinal = 0;
foreach (JsonFormatReader r in reader.EnumerateArray())
{
r.Merge(builder);
Assert.AreEqual(++ordinal, builder.Number);
}
Assert.AreEqual(3, ordinal);
Assert.AreEqual(3, builder.TextlinesCount);
}
[Test]
public void TestNestedMessageArray()
{
JsonFormatWriter writer = JsonFormatWriter.CreateInstance();
using (writer.StartArray())
{
using (writer.StartArray())
{
writer.WriteMessage(TestXmlMessage.CreateBuilder().SetNumber(1).AddTextlines("a").Build());
writer.WriteMessage(TestXmlMessage.CreateBuilder().SetNumber(2).AddTextlines("b").Build());
}
using (writer.StartArray())
writer.WriteMessage(TestXmlMessage.CreateBuilder().SetNumber(3).AddTextlines("c").Build());
}
string json = writer.ToString();
JsonFormatReader reader = JsonFormatReader.CreateInstance(json);
TestXmlMessage.Builder builder = TestXmlMessage.CreateBuilder();
int ordinal = 0;
foreach (JsonFormatReader r in reader.EnumerateArray())
foreach (JsonFormatReader r2 in r.EnumerateArray())
{
r2.Merge(builder);
Assert.AreEqual(++ordinal, builder.Number);
}
Assert.AreEqual(3, ordinal);
Assert.AreEqual(3, builder.TextlinesCount);
}
[Test]
public void TestReadWriteJsonWithoutRoot()
{
TestXmlMessage.Builder builder = TestXmlMessage.CreateBuilder();
TestXmlMessage message = builder.SetText("abc").SetNumber(123).Build();
string Json;
using (StringWriter sw = new StringWriter())
{
ICodedOutputStream output = JsonFormatWriter.CreateInstance(sw);
message.WriteTo(output);
output.Flush();
Json = sw.ToString();
}
Assert.AreEqual(@"""text"":""abc"",""number"":123", Json);
ICodedInputStream input = JsonFormatReader.CreateInstance(Json);
TestXmlMessage copy = TestXmlMessage.CreateBuilder().MergeFrom(input).Build();
Assert.AreEqual(message, copy);
}
[Test]
public void TestRecursiveLimit()
{
StringBuilder sb = new StringBuilder(8192);
for (int i = 0; i < 80; i++)
{
sb.Append("{\"child\":");
}
Assert.Throws<RecursionLimitExceededException>(() => Extensions.MergeFromJson(new TestXmlRescursive.Builder(), sb.ToString()).Build());
}
[Test]
public void FailWithEmptyText()
{
Assert.Throws<FormatException>(() => JsonFormatReader.CreateInstance("").Merge(TestXmlMessage.CreateBuilder()));
}
[Test]
public void FailWithUnexpectedValue()
{
Assert.Throws<FormatException>(() => JsonFormatReader.CreateInstance("{{}}").Merge(TestXmlMessage.CreateBuilder()));
}
[Test]
public void FailWithUnQuotedName()
{
Assert.Throws<FormatException>(() => JsonFormatReader.CreateInstance("{name:{}}").Merge(TestXmlMessage.CreateBuilder()));
}
[Test]
public void FailWithUnexpectedType()
{
Assert.Throws<FormatException>(() => JsonFormatReader.CreateInstance("{\"valid\":{}}").Merge(TestXmlMessage.CreateBuilder()));
}
// See issue 64 for background.
[Test]
public void ToJsonRequiringBufferExpansion()
{
string s = new string('.', 4086);
var opts = FileDescriptorProto.CreateBuilder()
.SetName(s)
.SetPackage("package")
.BuildPartial();
Assert.NotNull(Extensions.ToJson(opts));
}
}
}

@ -1,468 +0,0 @@
using System;
using System.IO;
using System.Text;
using System.Xml;
using Google.ProtocolBuffers.Serialization;
using Google.ProtocolBuffers.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers
{
public class TestWriterFormatXml
{
[Test]
public void Example_FromXml()
{
TestXmlMessage.Builder builder = TestXmlMessage.CreateBuilder();
XmlReader rdr = XmlReader.Create(new StringReader(@"<root><valid>true</valid></root>"));
//3.5: builder.MergeFromXml(rdr);
Extensions.MergeFromXml(builder, rdr);
TestXmlMessage message = builder.Build();
Assert.AreEqual(true, message.Valid);
}
[Test]
public void Example_ToXml()
{
TestXmlMessage message =
TestXmlMessage.CreateBuilder()
.SetValid(true)
.Build();
//3.5: string Xml = message.ToXml();
string Xml = Extensions.ToXml(message);
Assert.AreEqual(@"<root><valid>true</valid></root>", Xml);
}
[Test]
public void Example_WriteXmlUsingICodedOutputStream()
{
TestXmlMessage message =
TestXmlMessage.CreateBuilder()
.SetValid(true)
.Build();
using (TextWriter output = new StringWriter())
{
ICodedOutputStream writer = XmlFormatWriter.CreateInstance(output);
writer.WriteMessageStart(); //manually begin the message, output is '{'
ICodedOutputStream stream = writer;
message.WriteTo(stream); //write the message normally
writer.WriteMessageEnd(); //manually write the end message '}'
Assert.AreEqual(@"<root><valid>true</valid></root>", output.ToString());
}
}
[Test]
public void Example_ReadXmlUsingICodedInputStream()
{
TestXmlMessage.Builder builder = TestXmlMessage.CreateBuilder();
ICodedInputStream reader = XmlFormatReader.CreateInstance(@"<root><valid>true</valid></root>");
reader.ReadMessageStart(); //manually read the begin the message '{'
builder.MergeFrom(reader); //read the message normally
reader.ReadMessageEnd(); //manually read the end message '}'
}
[Test]
public void TestToXmlParseFromXml()
{
TestAllTypes msg = new TestAllTypes.Builder().SetDefaultBool(true).Build();
string xml = Extensions.ToXml(msg);
Assert.AreEqual("<root><default_bool>true</default_bool></root>", xml);
TestAllTypes copy = Extensions.MergeFromXml(new TestAllTypes.Builder(), XmlReader.Create(new StringReader(xml))).Build();
Assert.IsTrue(copy.HasDefaultBool && copy.DefaultBool);
Assert.AreEqual(msg, copy);
}
[Test]
public void TestToXmlParseFromXmlWithRootName()
{
TestAllTypes msg = new TestAllTypes.Builder().SetDefaultBool(true).Build();
string xml = Extensions.ToXml(msg, "message");
Assert.AreEqual("<message><default_bool>true</default_bool></message>", xml);
TestAllTypes copy = Extensions.MergeFromXml(new TestAllTypes.Builder(), "message", XmlReader.Create(new StringReader(xml))).Build();
Assert.IsTrue(copy.HasDefaultBool && copy.DefaultBool);
Assert.AreEqual(msg, copy);
}
[Test]
public void TestEmptyMessage()
{
TestXmlChild message = TestXmlChild.CreateBuilder()
.Build();
StringWriter sw = new StringWriter();
XmlWriter xw = XmlWriter.Create(sw);
//When we call message.WriteTo, we are responsible for the root element
xw.WriteStartElement("root");
message.WriteTo(XmlFormatWriter.CreateInstance(xw));
xw.WriteEndElement();
xw.Flush();
string xml = sw.ToString();
XmlFormatReader rdr = XmlFormatReader.CreateInstance(xml);
TestXmlChild copy = rdr.Merge(TestXmlChild.CreateBuilder()).Build();
Assert.AreEqual(message, copy);
}
[Test]
public void TestRepeatedField()
{
TestXmlChild message = TestXmlChild.CreateBuilder()
.AddOptions(EnumOptions.ONE)
.AddOptions(EnumOptions.TWO)
.Build();
//Allow the writer to write the root element
StringWriter sw = new StringWriter();
XmlFormatWriter.CreateInstance(sw).WriteMessage("root", message);
string xml = sw.ToString();
XmlFormatReader rdr = XmlFormatReader.CreateInstance(xml);
TestXmlChild copy = rdr.Merge(TestXmlChild.CreateBuilder()).Build();
Assert.AreEqual(message, copy);
}
[Test]
public void TestNestedEmptyMessage()
{
TestXmlMessage message = TestXmlMessage.CreateBuilder()
.SetChild(TestXmlChild.CreateBuilder().Build())
.Build();
StringWriter sw = new StringWriter();
XmlFormatWriter.CreateInstance(sw).WriteMessage("root", message);
string xml = sw.ToString();
XmlFormatReader rdr = XmlFormatReader.CreateInstance(xml);
TestXmlMessage copy = rdr.Merge(TestXmlMessage.CreateBuilder()).Build();
Assert.AreEqual(message, copy);
}
[Test]
public void TestNestedMessage()
{
TestXmlMessage message = TestXmlMessage.CreateBuilder()
.SetChild(TestXmlChild.CreateBuilder().AddOptions(EnumOptions.TWO).Build())
.Build();
StringWriter sw = new StringWriter();
XmlFormatWriter.CreateInstance(sw).WriteMessage("root", message);
string xml = sw.ToString();
XmlFormatReader rdr = XmlFormatReader.CreateInstance(xml);
TestXmlMessage copy = rdr.Merge(TestXmlMessage.CreateBuilder()).Build();
Assert.AreEqual(message, copy);
}
[Test]
public void TestBooleanTypes()
{
TestXmlMessage message = TestXmlMessage.CreateBuilder()
.SetValid(true)
.Build();
StringWriter sw = new StringWriter();
XmlFormatWriter.CreateInstance(sw).WriteMessage("root", message);
string xml = sw.ToString();
XmlFormatReader rdr = XmlFormatReader.CreateInstance(xml);
TestXmlMessage copy = rdr.Merge(TestXmlMessage.CreateBuilder()).Build();
Assert.AreEqual(message, copy);
}
[Test]
public void TestFullMessage()
{
TestXmlMessage message = TestXmlMessage.CreateBuilder()
.SetValid(true)
.SetText("text")
.AddTextlines("a")
.AddTextlines("b")
.AddTextlines("c")
.SetNumber(0x1010101010)
.AddNumbers(1)
.AddNumbers(2)
.AddNumbers(3)
.SetChild(TestXmlChild.CreateBuilder().AddOptions(EnumOptions.ONE).SetBinary(ByteString.CopyFrom(new byte[1])))
.AddChildren(TestXmlMessage.Types.Children.CreateBuilder().AddOptions(EnumOptions.TWO).SetBinary(ByteString.CopyFrom(new byte[2])))
.AddChildren(TestXmlMessage.Types.Children.CreateBuilder().AddOptions(EnumOptions.THREE).SetBinary(ByteString.CopyFrom(new byte[3])))
.Build();
StringWriter sw = new StringWriter();
XmlWriter xwtr = XmlWriter.Create(sw, new XmlWriterSettings {Indent = true, IndentChars = " "});
XmlFormatWriter.CreateInstance(xwtr).WriteMessage("root", message);
string xml = sw.ToString();
XmlFormatReader rdr = XmlFormatReader.CreateInstance(xml);
TestXmlMessage copy = rdr.Merge(TestXmlMessage.CreateBuilder()).Build();
Assert.AreEqual(message, copy);
}
[Test]
public void TestFullMessageWithRichTypes()
{
TestXmlMessage message = TestXmlMessage.CreateBuilder()
.SetValid(true)
.SetText("text")
.AddTextlines("a")
.AddTextlines("b")
.AddTextlines("c")
.SetNumber(0x1010101010)
.AddNumbers(1)
.AddNumbers(2)
.AddNumbers(3)
.SetChild(TestXmlChild.CreateBuilder().AddOptions(EnumOptions.ONE).SetBinary(ByteString.CopyFrom(new byte[1])))
.AddChildren(TestXmlMessage.Types.Children.CreateBuilder().AddOptions(EnumOptions.TWO).SetBinary(ByteString.CopyFrom(new byte[2])))
.AddChildren(TestXmlMessage.Types.Children.CreateBuilder().AddOptions(EnumOptions.THREE).SetBinary(ByteString.CopyFrom(new byte[3])))
.Build();
StringWriter sw = new StringWriter();
XmlWriter xwtr = XmlWriter.Create(sw, new XmlWriterSettings { Indent = true, IndentChars = " " });
XmlFormatWriter.CreateInstance(xwtr)
.SetOptions(XmlWriterOptions.OutputNestedArrays | XmlWriterOptions.OutputEnumValues)
.WriteMessage("root", message);
string xml = sw.ToString();
XmlFormatReader rdr = XmlFormatReader.CreateInstance(xml);
rdr.Options = XmlReaderOptions.ReadNestedArrays;
TestXmlMessage copy = rdr.Merge(TestXmlMessage.CreateBuilder()).Build();
Assert.AreEqual(message, copy);
}
[Test]
public void TestFullMessageWithUnknownFields()
{
TestXmlMessage origial = TestXmlMessage.CreateBuilder()
.SetValid(true)
.SetText("text")
.AddTextlines("a")
.AddTextlines("b")
.AddTextlines("c")
.SetNumber(0x1010101010)
.AddNumbers(1)
.AddNumbers(2)
.AddNumbers(3)
.SetChild(TestXmlChild.CreateBuilder().AddOptions(EnumOptions.ONE).SetBinary(ByteString.CopyFrom(new byte[1])))
.AddChildren(TestXmlMessage.Types.Children.CreateBuilder().AddOptions(EnumOptions.TWO).SetBinary(ByteString.CopyFrom(new byte[2])))
.AddChildren(TestXmlMessage.Types.Children.CreateBuilder().AddOptions(EnumOptions.THREE).SetBinary(ByteString.CopyFrom(new byte[3])))
.Build();
TestXmlNoFields message = TestXmlNoFields.CreateBuilder().MergeFrom(origial.ToByteArray()).Build();
Assert.AreEqual(0, message.AllFields.Count);
StringWriter sw = new StringWriter();
XmlFormatWriter.CreateInstance(sw)
.SetOptions(XmlWriterOptions.OutputNestedArrays | XmlWriterOptions.OutputEnumValues)
.WriteMessage("root", message);
string xml = sw.ToString();
using (XmlReader x = XmlReader.Create(new StringReader(xml)))
{
x.MoveToContent();
Assert.AreEqual(XmlNodeType.Element, x.NodeType);
//should always be empty
Assert.IsTrue(x.IsEmptyElement ||
(x.Read() && x.NodeType == XmlNodeType.EndElement)
);
}
XmlFormatReader rdr = XmlFormatReader.CreateInstance(xml);
rdr.Options = XmlReaderOptions.ReadNestedArrays;
TestXmlMessage copy = rdr.Merge(TestXmlMessage.CreateBuilder()).Build();
Assert.AreEqual(TestXmlMessage.DefaultInstance, copy);
}
[Test]
public void TestMessageWithXmlText()
{
TestXmlMessage message = TestXmlMessage.CreateBuilder()
.SetText("<text>").Build();
StringWriter sw = new StringWriter();
XmlFormatWriter.CreateInstance(sw).WriteMessage("root", message);
string xml = sw.ToString();
XmlFormatReader rdr = XmlFormatReader.CreateInstance(xml);
TestXmlMessage copy = rdr.Merge(TestXmlMessage.CreateBuilder()).Build();
Assert.AreEqual(message, copy);
}
[Test]
public void TestXmlWithWhitespace()
{
TestXmlMessage message = TestXmlMessage.CreateBuilder()
.SetText(" \t <- leading space and trailing -> \r\n\t").Build();
StringWriter sw = new StringWriter();
XmlFormatWriter.CreateInstance(sw).WriteMessage("root", message);
string xml = sw.ToString();
XmlFormatReader rdr = XmlFormatReader.CreateInstance(xml);
TestXmlMessage copy = rdr.Merge(TestXmlMessage.CreateBuilder()).Build();
Assert.AreEqual(message, copy);
}
[Test]
public void TestXmlWithExtensionText()
{
TestXmlMessage message = TestXmlMessage.CreateBuilder()
.SetExtension(UnittestExtrasXmltest.ExtensionText, " extension text value ! ")
.Build();
StringWriter sw = new StringWriter();
XmlFormatWriter.CreateInstance(sw).WriteMessage("root", message);
string xml = sw.ToString();
ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
UnittestExtrasXmltest.RegisterAllExtensions(registry);
XmlFormatReader rdr = XmlFormatReader.CreateInstance(xml);
TestXmlMessage copy = rdr.Merge(TestXmlMessage.CreateBuilder(), registry).Build();
Assert.AreEqual(message, copy);
}
[Test]
public void TestXmlWithExtensionMessage()
{
TestXmlMessage message = TestXmlMessage.CreateBuilder()
.SetExtension(UnittestExtrasXmltest.ExtensionMessage,
new TestXmlExtension.Builder().SetNumber(42).Build()).Build();
StringWriter sw = new StringWriter();
XmlFormatWriter.CreateInstance(sw).WriteMessage("root", message);
string xml = sw.ToString();
ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
UnittestExtrasXmltest.RegisterAllExtensions(registry);
XmlFormatReader rdr = XmlFormatReader.CreateInstance(xml);
TestXmlMessage copy = rdr.Merge(TestXmlMessage.CreateBuilder(), registry).Build();
Assert.AreEqual(message, copy);
}
[Test]
public void TestXmlWithExtensionArray()
{
TestXmlMessage message = TestXmlMessage.CreateBuilder()
.AddExtension(UnittestExtrasXmltest.ExtensionNumber, 100)
.AddExtension(UnittestExtrasXmltest.ExtensionNumber, 101)
.AddExtension(UnittestExtrasXmltest.ExtensionNumber, 102)
.Build();
StringWriter sw = new StringWriter();
XmlFormatWriter.CreateInstance(sw).WriteMessage("root", message);
string xml = sw.ToString();
ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
UnittestExtrasXmltest.RegisterAllExtensions(registry);
XmlFormatReader rdr = XmlFormatReader.CreateInstance(xml);
TestXmlMessage copy = rdr.Merge(TestXmlMessage.CreateBuilder(), registry).Build();
Assert.AreEqual(message, copy);
}
[Test]
public void TestXmlWithExtensionEnum()
{
TestXmlMessage message = TestXmlMessage.CreateBuilder()
.SetExtension(UnittestExtrasXmltest.ExtensionEnum, EnumOptions.ONE)
.Build();
StringWriter sw = new StringWriter();
XmlFormatWriter.CreateInstance(sw).WriteMessage("root", message);
string xml = sw.ToString();
ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
UnittestExtrasXmltest.RegisterAllExtensions(registry);
XmlFormatReader rdr = XmlFormatReader.CreateInstance(xml);
TestXmlMessage copy = rdr.Merge(TestXmlMessage.CreateBuilder(), registry).Build();
Assert.AreEqual(message, copy);
}
[Test]
public void TestXmlReadEmptyRoot()
{
TestXmlMessage.Builder builder = TestXmlMessage.CreateBuilder();
ICodedInputStream reader = XmlFormatReader.CreateInstance(@"<root/>");
reader.ReadMessageStart(); //manually read the begin the message '{'
builder.MergeFrom(reader); //write the message normally
reader.ReadMessageEnd(); //manually read the end message '}'
}
[Test]
public void TestXmlReadEmptyChild()
{
TestXmlMessage.Builder builder = TestXmlMessage.CreateBuilder();
ICodedInputStream reader = XmlFormatReader.CreateInstance(@"<root><text /></root>");
reader.ReadMessageStart(); //manually read the begin the message '{'
builder.MergeFrom(reader); //write the message normally
Assert.IsTrue(builder.HasText);
Assert.AreEqual(String.Empty, builder.Text);
}
[Test]
public void TestXmlReadWriteWithoutRoot()
{
TestXmlMessage.Builder builder = TestXmlMessage.CreateBuilder();
TestXmlMessage message = builder.SetText("abc").SetNumber(123).Build();
string xml;
using (StringWriter sw = new StringWriter())
{
ICodedOutputStream output = XmlFormatWriter.CreateInstance(
XmlWriter.Create(sw, new XmlWriterSettings() { ConformanceLevel = ConformanceLevel.Fragment }));
message.WriteTo(output);
output.Flush();
xml = sw.ToString();
}
Assert.AreEqual("<text>abc</text><number>123</number>", xml);
TestXmlMessage copy;
using (XmlReader xr = XmlReader.Create(new StringReader(xml), new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Fragment }))
{
ICodedInputStream input = XmlFormatReader.CreateInstance(xr);
copy = TestXmlMessage.CreateBuilder().MergeFrom(input).Build();
}
Assert.AreEqual(message, copy);
}
[Test]
public void TestRecursiveLimit()
{
StringBuilder sb = new StringBuilder(8192);
for (int i = 0; i < 80; i++)
{
sb.Append("<child>");
}
Assert.Throws<RecursionLimitExceededException>(() => Extensions.MergeFromXml(new TestXmlRescursive.Builder(), "child", XmlReader.Create(new StringReader(sb.ToString()))).Build());
}
}
}

@ -1,560 +0,0 @@
#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 Google.ProtocolBuffers.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers
{
public class TextFormatTest
{
private static readonly string AllFieldsSetText = TestResources.text_format_unittest_data;
private static readonly string AllExtensionsSetText = TestResources.text_format_unittest_extensions_data;
/// <summary>
/// Note that this is slightly different to the Java - 123.0 becomes 123, and 1.23E17 becomes 1.23E+17.
/// Both of these differences can be parsed by the Java and the C++, and we can parse their output too.
/// </summary>
private const string ExoticText =
"repeated_int32: -1\n" +
"repeated_int32: -2147483648\n" +
"repeated_int64: -1\n" +
"repeated_int64: -9223372036854775808\n" +
"repeated_uint32: 4294967295\n" +
"repeated_uint32: 2147483648\n" +
"repeated_uint64: 18446744073709551615\n" +
"repeated_uint64: 9223372036854775808\n" +
"repeated_double: 123\n" +
"repeated_double: 123.5\n" +
"repeated_double: 0.125\n" +
"repeated_double: 1.23E+17\n" +
"repeated_double: 1.235E+22\n" +
"repeated_double: 1.235E-18\n" +
"repeated_double: 123.456789\n" +
"repeated_double: Infinity\n" +
"repeated_double: -Infinity\n" +
"repeated_double: NaN\n" +
"repeated_string: \"\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"" +
"\\341\\210\\264\"\n" +
"repeated_bytes: \"\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"\\376\"\n";
private const string MessageSetText =
"[protobuf_unittest.TestMessageSetExtension1] {\n" +
" i: 123\n" +
"}\n" +
"[protobuf_unittest.TestMessageSetExtension2] {\n" +
" str: \"foo\"\n" +
"}\n";
/// <summary>
/// Print TestAllTypes and compare with golden file.
/// </summary>
[Test]
public void PrintMessage()
{
TestUtil.TestInMultipleCultures(() =>
{
string text = TextFormat.PrintToString(TestUtil.GetAllSet());
Assert.AreEqual(AllFieldsSetText.Replace("\r\n", "\n").Trim(),
text.Replace("\r\n", "\n").Trim());
});
}
/// <summary>
/// Tests that a builder prints the same way as a message.
/// </summary>
[Test]
public void PrintBuilder()
{
TestUtil.TestInMultipleCultures(() =>
{
string messageText = TextFormat.PrintToString(TestUtil.GetAllSet());
string builderText = TextFormat.PrintToString(TestUtil.GetAllSet().ToBuilder());
Assert.AreEqual(messageText, builderText);
});
}
/// <summary>
/// Print TestAllExtensions and compare with golden file.
/// </summary>
[Test]
public void PrintExtensions()
{
string text = TextFormat.PrintToString(TestUtil.GetAllExtensionsSet());
Assert.AreEqual(AllExtensionsSetText.Replace("\r\n", "\n").Trim(), text.Replace("\r\n", "\n").Trim());
}
/// <summary>
/// Test printing of unknown fields in a message.
/// </summary>
[Test]
public void PrintUnknownFields()
{
TestEmptyMessage message =
TestEmptyMessage.CreateBuilder()
.SetUnknownFields(
UnknownFieldSet.CreateBuilder()
.AddField(5,
UnknownField.CreateBuilder()
.AddVarint(1)
.AddFixed32(2)
.AddFixed64(3)
.AddLengthDelimited(ByteString.CopyFromUtf8("4"))
.AddGroup(
UnknownFieldSet.CreateBuilder()
.AddField(10,
UnknownField.CreateBuilder()
.AddVarint(5)
.Build())
.Build())
.Build())
.AddField(8,
UnknownField.CreateBuilder()
.AddVarint(1)
.AddVarint(2)
.AddVarint(3)
.Build())
.AddField(15,
UnknownField.CreateBuilder()
.AddVarint(0xABCDEF1234567890L)
.AddFixed32(0xABCD1234)
.AddFixed64(0xABCDEF1234567890L)
.Build())
.Build())
.Build();
Assert.AreEqual(
"5: 1\n" +
"5: 0x00000002\n" +
"5: 0x0000000000000003\n" +
"5: \"4\"\n" +
"5 {\n" +
" 10: 5\n" +
"}\n" +
"8: 1\n" +
"8: 2\n" +
"8: 3\n" +
"15: 12379813812177893520\n" +
"15: 0xabcd1234\n" +
"15: 0xabcdef1234567890\n",
TextFormat.PrintToString(message));
}
/// <summary>
/// Helper to construct a ByteString from a string containing only 8-bit
/// characters. The characters are converted directly to bytes, *not*
/// encoded using UTF-8.
/// </summary>
private static ByteString Bytes(string str)
{
byte[] bytes = new byte[str.Length];
for (int i = 0; i < bytes.Length; i++)
bytes[i] = (byte)str[i];
return ByteString.CopyFrom(bytes);
}
[Test]
public void PrintExotic()
{
IMessage message = TestAllTypes.CreateBuilder()
// Signed vs. unsigned numbers.
.AddRepeatedInt32(-1)
.AddRepeatedUint32(uint.MaxValue)
.AddRepeatedInt64(-1)
.AddRepeatedUint64(ulong.MaxValue)
.AddRepeatedInt32(1 << 31)
.AddRepeatedUint32(1U << 31)
.AddRepeatedInt64(1L << 63)
.AddRepeatedUint64(1UL << 63)
// Floats of various precisions and exponents.
.AddRepeatedDouble(123)
.AddRepeatedDouble(123.5)
.AddRepeatedDouble(0.125)
.AddRepeatedDouble(123e15)
.AddRepeatedDouble(123.5e20)
.AddRepeatedDouble(123.5e-20)
.AddRepeatedDouble(123.456789)
.AddRepeatedDouble(Double.PositiveInfinity)
.AddRepeatedDouble(Double.NegativeInfinity)
.AddRepeatedDouble(Double.NaN)
// Strings and bytes that needing escaping.
.AddRepeatedString("\0\u0001\u0007\b\f\n\r\t\v\\\'\"\u1234")
.AddRepeatedBytes(Bytes("\0\u0001\u0007\b\f\n\r\t\v\\\'\"\u00fe"))
.Build();
Assert.AreEqual(ExoticText, message.ToString());
}
[Test]
public void PrintMessageSet()
{
TestMessageSet messageSet =
TestMessageSet.CreateBuilder()
.SetExtension(
TestMessageSetExtension1.MessageSetExtension,
TestMessageSetExtension1.CreateBuilder().SetI(123).Build())
.SetExtension(
TestMessageSetExtension2.MessageSetExtension,
TestMessageSetExtension2.CreateBuilder().SetStr("foo").Build())
.Build();
Assert.AreEqual(MessageSetText, messageSet.ToString());
}
// =================================================================
[Test]
public void Parse()
{
TestUtil.TestInMultipleCultures(() =>
{
TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
TextFormat.Merge(AllFieldsSetText, builder);
TestUtil.AssertAllFieldsSet(builder.Build());
});
}
[Test]
public void ParseReader()
{
TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
TextFormat.Merge(new StringReader(AllFieldsSetText), builder);
TestUtil.AssertAllFieldsSet(builder.Build());
}
[Test]
public void ParseExtensions()
{
TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder();
TextFormat.Merge(AllExtensionsSetText,
TestUtil.CreateExtensionRegistry(),
builder);
TestUtil.AssertAllExtensionsSet(builder.Build());
}
[Test]
public void ParseCompatibility()
{
string original = "repeated_float: inf\n" +
"repeated_float: -inf\n" +
"repeated_float: nan\n" +
"repeated_float: inff\n" +
"repeated_float: -inff\n" +
"repeated_float: nanf\n" +
"repeated_float: 1.0f\n" +
"repeated_float: infinityf\n" +
"repeated_float: -Infinityf\n" +
"repeated_double: infinity\n" +
"repeated_double: -infinity\n" +
"repeated_double: nan\n";
string canonical = "repeated_float: Infinity\n" +
"repeated_float: -Infinity\n" +
"repeated_float: NaN\n" +
"repeated_float: Infinity\n" +
"repeated_float: -Infinity\n" +
"repeated_float: NaN\n" +
"repeated_float: 1\n" + // Java has 1.0; this is fine
"repeated_float: Infinity\n" +
"repeated_float: -Infinity\n" +
"repeated_double: Infinity\n" +
"repeated_double: -Infinity\n" +
"repeated_double: NaN\n";
TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
TextFormat.Merge(original, builder);
Assert.AreEqual(canonical, builder.Build().ToString());
}
[Test]
public void ParseExotic()
{
TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
TextFormat.Merge(ExoticText, builder);
// Too lazy to check things individually. Don't try to debug this
// if testPrintExotic() is Assert.Failing.
Assert.AreEqual(ExoticText, builder.Build().ToString());
}
[Test]
public void ParseMessageSet()
{
ExtensionRegistry extensionRegistry = ExtensionRegistry.CreateInstance();
extensionRegistry.Add(TestMessageSetExtension1.MessageSetExtension);
extensionRegistry.Add(TestMessageSetExtension2.MessageSetExtension);
TestMessageSet.Builder builder = TestMessageSet.CreateBuilder();
TextFormat.Merge(MessageSetText, extensionRegistry, builder);
TestMessageSet messageSet = builder.Build();
Assert.IsTrue(messageSet.HasExtension(TestMessageSetExtension1.MessageSetExtension));
Assert.AreEqual(123, messageSet.GetExtension(TestMessageSetExtension1.MessageSetExtension).I);
Assert.IsTrue(messageSet.HasExtension(TestMessageSetExtension2.MessageSetExtension));
Assert.AreEqual("foo", messageSet.GetExtension(TestMessageSetExtension2.MessageSetExtension).Str);
}
[Test]
public void ParseNumericEnum()
{
TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
TextFormat.Merge("optional_nested_enum: 2", builder);
Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAR, builder.OptionalNestedEnum);
}
[Test]
public void ParseAngleBrackets()
{
TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
TextFormat.Merge("OptionalGroup: < a: 1 >", builder);
Assert.IsTrue(builder.HasOptionalGroup);
Assert.AreEqual(1, builder.OptionalGroup.A);
}
[Test]
public void ParseComment()
{
TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
TextFormat.Merge(
"# this is a comment\n" +
"optional_int32: 1 # another comment\n" +
"optional_int64: 2\n" +
"# EOF comment", builder);
Assert.AreEqual(1, builder.OptionalInt32);
Assert.AreEqual(2, builder.OptionalInt64);
}
private static void AssertParseError(string error, string text)
{
TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
Exception exception = Assert.Throws<FormatException>(() => TextFormat.Merge(text, TestUtil.CreateExtensionRegistry(), builder));
Assert.AreEqual(error, exception.Message);
}
[Test]
public void ParseErrors()
{
AssertParseError(
"1:16: Expected \":\".",
"optional_int32 123");
AssertParseError(
"1:23: Expected identifier.",
"optional_nested_enum: ?");
AssertParseError(
"1:18: Couldn't parse integer: Number must be positive: -1",
"optional_uint32: -1");
AssertParseError(
"1:17: Couldn't parse integer: Number out of range for 32-bit signed " +
"integer: 82301481290849012385230157",
"optional_int32: 82301481290849012385230157");
AssertParseError(
"1:16: Expected \"true\" or \"false\".",
"optional_bool: maybe");
AssertParseError(
"1:18: Expected string.",
"optional_string: 123");
AssertParseError(
"1:18: String missing ending quote.",
"optional_string: \"ueoauaoe");
AssertParseError(
"1:18: String missing ending quote.",
"optional_string: \"ueoauaoe\n" +
"optional_int32: 123");
AssertParseError(
"1:18: Invalid escape sequence: '\\z'",
"optional_string: \"\\z\"");
AssertParseError(
"1:18: String missing ending quote.",
"optional_string: \"ueoauaoe\n" +
"optional_int32: 123");
AssertParseError(
"1:2: Extension \"nosuchext\" not found in the ExtensionRegistry.",
"[nosuchext]: 123");
AssertParseError(
"1:20: Extension \"protobuf_unittest.optional_int32_extension\" " +
"not found in the ExtensionRegistry.",
"[protobuf_unittest.optional_int32_extension]: 123");
AssertParseError(
"1:1: Message type \"protobuf_unittest.TestAllTypes\" has no field " +
"named \"nosuchfield\".",
"nosuchfield: 123");
AssertParseError(
"1:21: Expected \">\".",
"OptionalGroup < a: 1");
AssertParseError(
"1:23: Enum type \"protobuf_unittest.TestAllTypes.NestedEnum\" has no " +
"value named \"NO_SUCH_VALUE\".",
"optional_nested_enum: NO_SUCH_VALUE");
AssertParseError(
"1:23: Enum type \"protobuf_unittest.TestAllTypes.NestedEnum\" has no " +
"value with number 123.",
"optional_nested_enum: 123");
// Delimiters must match.
AssertParseError(
"1:22: Expected identifier.",
"OptionalGroup < a: 1 }");
AssertParseError(
"1:22: Expected identifier.",
"OptionalGroup { a: 1 >");
}
// =================================================================
private static ByteString Bytes(params byte[] bytes)
{
return ByteString.CopyFrom(bytes);
}
[Test]
public void Escape()
{
// Escape sequences.
Assert.AreEqual("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"",
TextFormat.EscapeBytes(Bytes("\0\u0001\u0007\b\f\n\r\t\v\\\'\"")));
Assert.AreEqual("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\"",
TextFormat.EscapeText("\0\u0001\u0007\b\f\n\r\t\v\\\'\""));
Assert.AreEqual(Bytes("\0\u0001\u0007\b\f\n\r\t\v\\\'\""),
TextFormat.UnescapeBytes("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\""));
Assert.AreEqual("\0\u0001\u0007\b\f\n\r\t\v\\\'\"",
TextFormat.UnescapeText("\\000\\001\\a\\b\\f\\n\\r\\t\\v\\\\\\'\\\""));
// Unicode handling.
Assert.AreEqual("\\341\\210\\264", TextFormat.EscapeText("\u1234"));
Assert.AreEqual("\\341\\210\\264", TextFormat.EscapeBytes(Bytes(0xe1, 0x88, 0xb4)));
Assert.AreEqual("\u1234", TextFormat.UnescapeText("\\341\\210\\264"));
Assert.AreEqual(Bytes(0xe1, 0x88, 0xb4), TextFormat.UnescapeBytes("\\341\\210\\264"));
Assert.AreEqual("\u1234", TextFormat.UnescapeText("\\xe1\\x88\\xb4"));
Assert.AreEqual(Bytes(0xe1, 0x88, 0xb4), TextFormat.UnescapeBytes("\\xe1\\x88\\xb4"));
// Errors.
Assert.Throws<FormatException>(() => TextFormat.UnescapeText("\\x"));
Assert.Throws<FormatException>(() => TextFormat.UnescapeText("\\z"));
Assert.Throws<FormatException>(() => TextFormat.UnescapeText("\\"));
}
[Test]
public void ParseInteger()
{
Assert.AreEqual(0, TextFormat.ParseInt32("0"));
Assert.AreEqual(1, TextFormat.ParseInt32("1"));
Assert.AreEqual(-1, TextFormat.ParseInt32("-1"));
Assert.AreEqual(12345, TextFormat.ParseInt32("12345"));
Assert.AreEqual(-12345, TextFormat.ParseInt32("-12345"));
Assert.AreEqual(2147483647, TextFormat.ParseInt32("2147483647"));
Assert.AreEqual(-2147483648, TextFormat.ParseInt32("-2147483648"));
Assert.AreEqual(0u, TextFormat.ParseUInt32("0"));
Assert.AreEqual(1u, TextFormat.ParseUInt32("1"));
Assert.AreEqual(12345u, TextFormat.ParseUInt32("12345"));
Assert.AreEqual(2147483647u, TextFormat.ParseUInt32("2147483647"));
Assert.AreEqual(2147483648U, TextFormat.ParseUInt32("2147483648"));
Assert.AreEqual(4294967295U, TextFormat.ParseUInt32("4294967295"));
Assert.AreEqual(0L, TextFormat.ParseInt64("0"));
Assert.AreEqual(1L, TextFormat.ParseInt64("1"));
Assert.AreEqual(-1L, TextFormat.ParseInt64("-1"));
Assert.AreEqual(12345L, TextFormat.ParseInt64("12345"));
Assert.AreEqual(-12345L, TextFormat.ParseInt64("-12345"));
Assert.AreEqual(2147483647L, TextFormat.ParseInt64("2147483647"));
Assert.AreEqual(-2147483648L, TextFormat.ParseInt64("-2147483648"));
Assert.AreEqual(4294967295L, TextFormat.ParseInt64("4294967295"));
Assert.AreEqual(4294967296L, TextFormat.ParseInt64("4294967296"));
Assert.AreEqual(9223372036854775807L, TextFormat.ParseInt64("9223372036854775807"));
Assert.AreEqual(-9223372036854775808L, TextFormat.ParseInt64("-9223372036854775808"));
Assert.AreEqual(0uL, TextFormat.ParseUInt64("0"));
Assert.AreEqual(1uL, TextFormat.ParseUInt64("1"));
Assert.AreEqual(12345uL, TextFormat.ParseUInt64("12345"));
Assert.AreEqual(2147483647uL, TextFormat.ParseUInt64("2147483647"));
Assert.AreEqual(4294967295uL, TextFormat.ParseUInt64("4294967295"));
Assert.AreEqual(4294967296uL, TextFormat.ParseUInt64("4294967296"));
Assert.AreEqual(9223372036854775807UL, TextFormat.ParseUInt64("9223372036854775807"));
Assert.AreEqual(9223372036854775808UL, TextFormat.ParseUInt64("9223372036854775808"));
Assert.AreEqual(18446744073709551615UL, TextFormat.ParseUInt64("18446744073709551615"));
// Hex
Assert.AreEqual(0x1234abcd, TextFormat.ParseInt32("0x1234abcd"));
Assert.AreEqual(-0x1234abcd, TextFormat.ParseInt32("-0x1234abcd"));
Assert.AreEqual(0xffffffffffffffffUL, TextFormat.ParseUInt64("0xffffffffffffffff"));
Assert.AreEqual(0x7fffffffffffffffL,
TextFormat.ParseInt64("0x7fffffffffffffff"));
// Octal
Assert.AreEqual(342391, TextFormat.ParseInt32("01234567"));
// Out-of-range
Assert.Throws<FormatException>(() => TextFormat.ParseInt32("2147483648"));
Assert.Throws<FormatException>(() => TextFormat.ParseInt32("-2147483649"));
Assert.Throws<FormatException>(() => TextFormat.ParseUInt32("4294967296"));
Assert.Throws<FormatException>(() => TextFormat.ParseUInt32("-1"));
Assert.Throws<FormatException>(() => TextFormat.ParseInt64("9223372036854775808"));
Assert.Throws<FormatException>(() => TextFormat.ParseInt64("-9223372036854775809"));
Assert.Throws<FormatException>(() => TextFormat.ParseUInt64("18446744073709551616"));
Assert.Throws<FormatException>(() => TextFormat.ParseUInt64("-1"));
Assert.Throws<FormatException>(() => TextFormat.ParseInt32("abcd"));
}
[Test]
public void ParseLongString()
{
string longText =
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890" +
"123456789012345678901234567890123456789012345678901234567890";
TestAllTypes.Builder builder = TestAllTypes.CreateBuilder();
TextFormat.Merge("optional_string: \"" + longText + "\"", builder);
Assert.AreEqual(longText, builder.OptionalString);
}
}
}

@ -1,431 +0,0 @@
#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.Collections.Generic;
using Google.ProtocolBuffers.Descriptors;
using Google.ProtocolBuffers.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers
{
public class UnknownFieldSetTest
{
private readonly MessageDescriptor descriptor;
private readonly TestAllTypes allFields;
private readonly ByteString allFieldsData;
/// <summary>
/// An empty message that has been parsed from allFieldsData. So, it has
/// unknown fields of every type.
/// </summary>
private readonly TestEmptyMessage emptyMessage;
private readonly UnknownFieldSet unknownFields;
public UnknownFieldSetTest()
{
descriptor = TestAllTypes.Descriptor;
allFields = TestUtil.GetAllSet();
allFieldsData = allFields.ToByteString();
emptyMessage = TestEmptyMessage.ParseFrom(allFieldsData);
unknownFields = emptyMessage.UnknownFields;
}
private UnknownField GetField(String name)
{
FieldDescriptor field = descriptor.FindDescriptor<FieldDescriptor>(name);
Assert.NotNull(field);
return unknownFields.FieldDictionary[field.FieldNumber];
}
/// <summary>
/// Constructs a protocol buffer which contains fields with all the same
/// numbers as allFieldsData except that each field is some other wire
/// type.
/// </summary>
private ByteString GetBizarroData()
{
UnknownFieldSet.Builder bizarroFields = UnknownFieldSet.CreateBuilder();
UnknownField varintField = UnknownField.CreateBuilder().AddVarint(1).Build();
UnknownField fixed32Field = UnknownField.CreateBuilder().AddFixed32(1).Build();
foreach (KeyValuePair<int, UnknownField> entry in unknownFields.FieldDictionary)
{
if (entry.Value.VarintList.Count == 0)
{
// Original field is not a varint, so use a varint.
bizarroFields.AddField(entry.Key, varintField);
}
else
{
// Original field *is* a varint, so use something else.
bizarroFields.AddField(entry.Key, fixed32Field);
}
}
return bizarroFields.Build().ToByteString();
}
// =================================================================
[Test]
public void Varint()
{
UnknownField field = GetField("optional_int32");
Assert.AreEqual(1, field.VarintList.Count);
Assert.AreEqual(allFields.OptionalInt32, (long) field.VarintList[0]);
}
[Test]
public void Fixed32()
{
UnknownField field = GetField("optional_fixed32");
Assert.AreEqual(1, field.Fixed32List.Count);
Assert.AreEqual(allFields.OptionalFixed32, (int) field.Fixed32List[0]);
}
[Test]
public void Fixed64()
{
UnknownField field = GetField("optional_fixed64");
Assert.AreEqual(1, field.Fixed64List.Count);
Assert.AreEqual((long)allFields.OptionalFixed64, (long)field.Fixed64List[0]);
}
[Test]
public void LengthDelimited()
{
UnknownField field = GetField("optional_bytes");
Assert.AreEqual(1, field.LengthDelimitedList.Count);
Assert.AreEqual(allFields.OptionalBytes, field.LengthDelimitedList[0]);
}
[Test]
public void Group()
{
FieldDescriptor nestedFieldDescriptor =
TestAllTypes.Types.OptionalGroup.Descriptor.FindDescriptor<FieldDescriptor>("a");
Assert.NotNull(nestedFieldDescriptor);
UnknownField field = GetField("optionalgroup");
Assert.AreEqual(1, field.GroupList.Count);
UnknownFieldSet group = field.GroupList[0];
Assert.AreEqual(1, group.FieldDictionary.Count);
Assert.IsTrue(group.HasField(nestedFieldDescriptor.FieldNumber));
UnknownField nestedField = group[nestedFieldDescriptor.FieldNumber];
Assert.AreEqual(1, nestedField.VarintList.Count);
Assert.AreEqual(allFields.OptionalGroup.A, (long) nestedField.VarintList[0]);
}
[Test]
public void Serialize()
{
// Check that serializing the UnknownFieldSet produces the original data again.
ByteString data = emptyMessage.ToByteString();
Assert.AreEqual(allFieldsData, data);
}
[Test]
public void CopyFrom()
{
TestEmptyMessage message =
TestEmptyMessage.CreateBuilder().MergeFrom(emptyMessage).Build();
Assert.AreEqual(emptyMessage.ToString(), message.ToString());
}
[Test]
public void MergeFrom()
{
TestEmptyMessage source =
TestEmptyMessage.CreateBuilder()
.SetUnknownFields(
UnknownFieldSet.CreateBuilder()
.AddField(2,
UnknownField.CreateBuilder()
.AddVarint(2).Build())
.AddField(3,
UnknownField.CreateBuilder()
.AddVarint(4).Build())
.Build())
.Build();
TestEmptyMessage destination =
TestEmptyMessage.CreateBuilder()
.SetUnknownFields(
UnknownFieldSet.CreateBuilder()
.AddField(1,
UnknownField.CreateBuilder()
.AddVarint(1).Build())
.AddField(3,
UnknownField.CreateBuilder()
.AddVarint(3).Build())
.Build())
.MergeFrom(source)
.Build();
Assert.AreEqual(
"1: 1\n" +
"2: 2\n" +
"3: 3\n" +
"3: 4\n",
destination.ToString());
}
[Test]
public void Clear()
{
UnknownFieldSet fields =
UnknownFieldSet.CreateBuilder().MergeFrom(unknownFields).Clear().Build();
Assert.AreEqual(0, fields.FieldDictionary.Count);
}
[Test]
public void ClearMessage()
{
TestEmptyMessage message =
TestEmptyMessage.CreateBuilder().MergeFrom(emptyMessage).Clear().Build();
Assert.AreEqual(0, message.SerializedSize);
}
[Test]
public void ParseKnownAndUnknown()
{
// Test mixing known and unknown fields when parsing.
UnknownFieldSet fields =
UnknownFieldSet.CreateBuilder(unknownFields)
.AddField(123456,
UnknownField.CreateBuilder().AddVarint(654321).Build())
.Build();
ByteString data = fields.ToByteString();
TestAllTypes destination = TestAllTypes.ParseFrom(data);
TestUtil.AssertAllFieldsSet(destination);
Assert.AreEqual(1, destination.UnknownFields.FieldDictionary.Count);
UnknownField field = destination.UnknownFields[123456];
Assert.AreEqual(1, field.VarintList.Count);
Assert.AreEqual(654321, (long) field.VarintList[0]);
}
[Test]
public void WrongTypeTreatedAsUnknown()
{
// Test that fields of the wrong wire type are treated like unknown fields
// when parsing.
ByteString bizarroData = GetBizarroData();
TestAllTypes allTypesMessage = TestAllTypes.ParseFrom(bizarroData);
TestEmptyMessage emptyMessage = TestEmptyMessage.ParseFrom(bizarroData);
// All fields should have been interpreted as unknown, so the debug strings
// should be the same.
Assert.AreEqual(emptyMessage.ToString(), allTypesMessage.ToString());
}
[Test]
public void UnknownExtensions()
{
// Make sure fields are properly parsed to the UnknownFieldSet even when
// they are declared as extension numbers.
TestEmptyMessageWithExtensions message =
TestEmptyMessageWithExtensions.ParseFrom(allFieldsData);
Assert.AreEqual(unknownFields.FieldDictionary.Count,
message.UnknownFields.FieldDictionary.Count);
Assert.AreEqual(allFieldsData, message.ToByteString());
}
[Test]
public void WrongExtensionTypeTreatedAsUnknown()
{
// Test that fields of the wrong wire type are treated like unknown fields
// when parsing extensions.
ByteString bizarroData = GetBizarroData();
TestAllExtensions allExtensionsMessage = TestAllExtensions.ParseFrom(bizarroData);
TestEmptyMessage emptyMessage = TestEmptyMessage.ParseFrom(bizarroData);
// All fields should have been interpreted as unknown, so the debug strings
// should be the same.
Assert.AreEqual(emptyMessage.ToString(),
allExtensionsMessage.ToString());
}
[Test]
public void ParseUnknownEnumValue()
{
FieldDescriptor singularField =
TestAllTypes.Descriptor.FindDescriptor<FieldDescriptor>("optional_nested_enum");
FieldDescriptor repeatedField =
TestAllTypes.Descriptor.FindDescriptor<FieldDescriptor>("repeated_nested_enum");
Assert.NotNull(singularField);
Assert.NotNull(repeatedField);
ByteString data =
UnknownFieldSet.CreateBuilder()
.AddField(singularField.FieldNumber,
UnknownField.CreateBuilder()
.AddVarint((int) TestAllTypes.Types.NestedEnum.BAR)
.AddVarint(5) // not valid
.Build())
.AddField(repeatedField.FieldNumber,
UnknownField.CreateBuilder()
.AddVarint((int) TestAllTypes.Types.NestedEnum.FOO)
.AddVarint(4) // not valid
.AddVarint((int) TestAllTypes.Types.NestedEnum.BAZ)
.AddVarint(6) // not valid
.Build())
.Build()
.ToByteString();
{
TestAllTypes message = TestAllTypes.ParseFrom(data);
Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAR,
message.OptionalNestedEnum);
TestUtil.AssertEqual(new[] {TestAllTypes.Types.NestedEnum.FOO, TestAllTypes.Types.NestedEnum.BAZ},
message.RepeatedNestedEnumList);
TestUtil.AssertEqual(new[] {5UL}, message.UnknownFields[singularField.FieldNumber].VarintList);
TestUtil.AssertEqual(new[] {4UL, 6UL}, message.UnknownFields[repeatedField.FieldNumber].VarintList);
}
{
TestAllExtensions message =
TestAllExtensions.ParseFrom(data, TestUtil.CreateExtensionRegistry());
Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAR,
message.GetExtension(Unittest.OptionalNestedEnumExtension));
TestUtil.AssertEqual(new[] {TestAllTypes.Types.NestedEnum.FOO, TestAllTypes.Types.NestedEnum.BAZ},
message.GetExtension(Unittest.RepeatedNestedEnumExtension));
TestUtil.AssertEqual(new[] {5UL}, message.UnknownFields[singularField.FieldNumber].VarintList);
TestUtil.AssertEqual(new[] {4UL, 6UL}, message.UnknownFields[repeatedField.FieldNumber].VarintList);
}
}
[Test]
public void LargeVarint()
{
ByteString data =
UnknownFieldSet.CreateBuilder()
.AddField(1,
UnknownField.CreateBuilder()
.AddVarint(0x7FFFFFFFFFFFFFFFL)
.Build())
.Build()
.ToByteString();
UnknownFieldSet parsed = UnknownFieldSet.ParseFrom(data);
UnknownField field = parsed[1];
Assert.AreEqual(1, field.VarintList.Count);
Assert.AreEqual(0x7FFFFFFFFFFFFFFFUL, field.VarintList[0]);
}
[Test]
public void EqualsAndHashCode()
{
UnknownField fixed32Field = UnknownField.CreateBuilder().AddFixed32(1).Build();
UnknownField fixed64Field = UnknownField.CreateBuilder().AddFixed64(1).Build();
UnknownField varIntField = UnknownField.CreateBuilder().AddVarint(1).Build();
UnknownField lengthDelimitedField =
UnknownField.CreateBuilder().AddLengthDelimited(ByteString.Empty).Build();
UnknownField groupField = UnknownField.CreateBuilder().AddGroup(unknownFields).Build();
UnknownFieldSet a = UnknownFieldSet.CreateBuilder().AddField(1, fixed32Field).Build();
UnknownFieldSet b = UnknownFieldSet.CreateBuilder().AddField(1, fixed64Field).Build();
UnknownFieldSet c = UnknownFieldSet.CreateBuilder().AddField(1, varIntField).Build();
UnknownFieldSet d = UnknownFieldSet.CreateBuilder().AddField(1, lengthDelimitedField).Build();
UnknownFieldSet e = UnknownFieldSet.CreateBuilder().AddField(1, groupField).Build();
CheckEqualsIsConsistent(a);
CheckEqualsIsConsistent(b);
CheckEqualsIsConsistent(c);
CheckEqualsIsConsistent(d);
CheckEqualsIsConsistent(e);
CheckNotEqual(a, b);
CheckNotEqual(a, c);
CheckNotEqual(a, d);
CheckNotEqual(a, e);
CheckNotEqual(b, c);
CheckNotEqual(b, d);
CheckNotEqual(b, e);
CheckNotEqual(c, d);
CheckNotEqual(c, e);
CheckNotEqual(d, e);
}
/// <summary>
/// Asserts that the given field sets are not equal and have different
/// hash codes.
/// </summary>
/// <remarks>
/// It's valid for non-equal objects to have the same hash code, so
/// this test is stricter than it needs to be. However, this should happen
/// relatively rarely.
/// </remarks>
/// <param name="s1"></param>
/// <param name="s2"></param>
private static void CheckNotEqual(UnknownFieldSet s1, UnknownFieldSet s2)
{
String equalsError = string.Format("{0} should not be equal to {1}", s1, s2);
Assert.IsFalse(s1.Equals(s2), equalsError);
Assert.IsFalse(s2.Equals(s1), equalsError);
Assert.IsFalse(s1.GetHashCode() == s2.GetHashCode(),
string.Format("{0} should have a different hash code from {1}", s1, s2));
}
/**
* Asserts that the given field sets are equal and have identical hash codes.
*/
private static void CheckEqualsIsConsistent(UnknownFieldSet set)
{
// Object should be equal to itself.
Assert.AreEqual(set, set);
// Object should be equal to a copy of itself.
UnknownFieldSet copy = UnknownFieldSet.CreateBuilder(set).Build();
Assert.AreEqual(set, copy);
Assert.AreEqual(copy, set);
Assert.AreEqual(set.GetHashCode(), copy.GetHashCode());
}
}
}

@ -34,13 +34,11 @@
#endregion
using System.IO;
using System.Reflection;
using Google.ProtocolBuffers.Descriptors;
using Google.ProtocolBuffers.TestProtos;
using Google.Protobuf.Descriptors;
using NUnit.Framework;
namespace Google.ProtocolBuffers
namespace Google.Protobuf
{
public class WireFormatTest
{
@ -58,254 +56,5 @@ namespace Google.ProtocolBuffers
Assert.AreEqual(mapping.WireType, WireFormat.GetWireType(fieldType));
}
}
[Test]
public void Serialization()
{
TestAllTypes message = TestUtil.GetAllSet();
ByteString rawBytes = message.ToByteString();
Assert.AreEqual(rawBytes.Length, message.SerializedSize);
TestAllTypes message2 = TestAllTypes.ParseFrom(rawBytes);
TestUtil.AssertAllFieldsSet(message2);
}
[Test]
public void SerializationPacked()
{
TestPackedTypes message = TestUtil.GetPackedSet();
ByteString rawBytes = message.ToByteString();
Assert.AreEqual(rawBytes.Length, message.SerializedSize);
TestPackedTypes message2 = TestPackedTypes.ParseFrom(rawBytes);
TestUtil.AssertPackedFieldsSet(message2);
}
[Test]
public void SerializeExtensions()
{
// TestAllTypes and TestAllExtensions should have compatible wire formats,
// so if we serialize a TestAllExtensions then parse it as TestAllTypes
// it should work.
TestAllExtensions message = TestUtil.GetAllExtensionsSet();
ByteString rawBytes = message.ToByteString();
Assert.AreEqual(rawBytes.Length, message.SerializedSize);
TestAllTypes message2 = TestAllTypes.ParseFrom(rawBytes);
TestUtil.AssertAllFieldsSet(message2);
}
[Test]
public void SerializePackedExtensions()
{
// TestPackedTypes and TestPackedExtensions should have compatible wire
// formats; check that they serialize to the same string.
TestPackedExtensions message = TestUtil.GetPackedExtensionsSet();
ByteString rawBytes = message.ToByteString();
TestPackedTypes message2 = TestUtil.GetPackedSet();
ByteString rawBytes2 = message2.ToByteString();
Assert.AreEqual(rawBytes, rawBytes2);
}
[Test]
public void SerializeDelimited()
{
MemoryStream stream = new MemoryStream();
TestUtil.GetAllSet().WriteDelimitedTo(stream);
stream.WriteByte(12);
TestUtil.GetPackedSet().WriteDelimitedTo(stream);
stream.WriteByte(34);
stream.Position = 0;
TestUtil.AssertAllFieldsSet(TestAllTypes.ParseDelimitedFrom(stream));
Assert.AreEqual(12, stream.ReadByte());
TestUtil.AssertPackedFieldsSet(TestPackedTypes.ParseDelimitedFrom(stream));
Assert.AreEqual(34, stream.ReadByte());
Assert.AreEqual(-1, stream.ReadByte());
}
[Test]
public void ParseExtensions()
{
// TestAllTypes and TestAllExtensions should have compatible wire formats,
// so if we serealize a TestAllTypes then parse it as TestAllExtensions
// it should work.
TestAllTypes message = TestUtil.GetAllSet();
ByteString rawBytes = message.ToByteString();
ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
TestUtil.RegisterAllExtensions(registry);
registry = registry.AsReadOnly();
TestAllExtensions message2 = TestAllExtensions.ParseFrom(rawBytes, registry);
TestUtil.AssertAllExtensionsSet(message2);
}
[Test]
public void ParsePackedExtensions()
{
// Ensure that packed extensions can be properly parsed.
TestPackedExtensions message = TestUtil.GetPackedExtensionsSet();
ByteString rawBytes = message.ToByteString();
ExtensionRegistry registry = TestUtil.CreateExtensionRegistry();
TestPackedExtensions message2 = TestPackedExtensions.ParseFrom(rawBytes, registry);
TestUtil.AssertPackedExtensionsSet(message2);
}
[Test]
public void ExtensionsSerializedSize()
{
Assert.IsTrue(TestUtil.GetAllSet().SerializedSize < TestUtil.GetAllExtensionsSet().SerializedSize);
}
private static void AssertFieldsInOrder(ByteString data)
{
CodedInputStream input = data.CreateCodedInput();
uint previousTag = 0;
uint tag;
string name;
while (input.ReadTag(out tag, out name))
{
Assert.IsTrue(tag > previousTag);
previousTag = tag;
input.SkipField();
}
}
[Test]
public void InterleavedFieldsAndExtensions()
{
// Tests that fields are written in order even when extension ranges
// are interleaved with field numbers.
ByteString data =
TestFieldOrderings.CreateBuilder()
.SetMyInt(1)
.SetMyString("foo")
.SetMyFloat(1.0F)
.SetExtension(Unittest.MyExtensionInt, 23)
.SetExtension(Unittest.MyExtensionString, "bar")
.Build().ToByteString();
AssertFieldsInOrder(data);
MessageDescriptor descriptor = TestFieldOrderings.Descriptor;
ByteString dynamic_data =
DynamicMessage.CreateBuilder(TestFieldOrderings.Descriptor)
.SetField(descriptor.FindDescriptor<FieldDescriptor>("my_int"), 1L)
.SetField(descriptor.FindDescriptor<FieldDescriptor>("my_string"), "foo")
.SetField(descriptor.FindDescriptor<FieldDescriptor>("my_float"), 1.0F)
.SetField(Unittest.MyExtensionInt.Descriptor, 23)
.SetField(Unittest.MyExtensionString.Descriptor, "bar")
.WeakBuild().ToByteString();
AssertFieldsInOrder(dynamic_data);
}
private const int UnknownTypeId = 1550055;
private static readonly int TypeId1 = TestMessageSetExtension1.Descriptor.Extensions[0].FieldNumber;
private static readonly int TypeId2 = TestMessageSetExtension2.Descriptor.Extensions[0].FieldNumber;
[Test]
public void SerializeMessageSet()
{
// Set up a TestMessageSet with two known messages and an unknown one.
TestMessageSet messageSet =
TestMessageSet.CreateBuilder()
.SetExtension(
TestMessageSetExtension1.MessageSetExtension,
TestMessageSetExtension1.CreateBuilder().SetI(123).Build())
.SetExtension(
TestMessageSetExtension2.MessageSetExtension,
TestMessageSetExtension2.CreateBuilder().SetStr("foo").Build())
.SetUnknownFields(
UnknownFieldSet.CreateBuilder()
.AddField(UnknownTypeId,
UnknownField.CreateBuilder()
.AddLengthDelimited(ByteString.CopyFromUtf8("bar"))
.Build())
.Build())
.Build();
ByteString data = messageSet.ToByteString();
// Parse back using RawMessageSet and check the contents.
RawMessageSet raw = RawMessageSet.ParseFrom(data);
Assert.AreEqual(0, raw.UnknownFields.FieldDictionary.Count);
Assert.AreEqual(3, raw.ItemCount);
Assert.AreEqual(TypeId1, raw.ItemList[0].TypeId);
Assert.AreEqual(TypeId2, raw.ItemList[1].TypeId);
Assert.AreEqual(UnknownTypeId, raw.ItemList[2].TypeId);
TestMessageSetExtension1 message1 = TestMessageSetExtension1.ParseFrom(raw.GetItem(0).Message.ToByteArray());
Assert.AreEqual(123, message1.I);
TestMessageSetExtension2 message2 = TestMessageSetExtension2.ParseFrom(raw.GetItem(1).Message.ToByteArray());
Assert.AreEqual("foo", message2.Str);
Assert.AreEqual("bar", raw.GetItem(2).Message.ToStringUtf8());
}
[Test]
public void ParseMessageSet()
{
ExtensionRegistry extensionRegistry = ExtensionRegistry.CreateInstance();
extensionRegistry.Add(TestMessageSetExtension1.MessageSetExtension);
extensionRegistry.Add(TestMessageSetExtension2.MessageSetExtension);
// Set up a RawMessageSet with two known messages and an unknown one.
RawMessageSet raw =
RawMessageSet.CreateBuilder()
.AddItem(
RawMessageSet.Types.Item.CreateBuilder()
.SetTypeId(TypeId1)
.SetMessage(
TestMessageSetExtension1.CreateBuilder()
.SetI(123)
.Build().ToByteString())
.Build())
.AddItem(
RawMessageSet.Types.Item.CreateBuilder()
.SetTypeId(TypeId2)
.SetMessage(
TestMessageSetExtension2.CreateBuilder()
.SetStr("foo")
.Build().ToByteString())
.Build())
.AddItem(
RawMessageSet.Types.Item.CreateBuilder()
.SetTypeId(UnknownTypeId)
.SetMessage(ByteString.CopyFromUtf8("bar"))
.Build())
.Build();
ByteString data = raw.ToByteString();
// Parse as a TestMessageSet and check the contents.
TestMessageSet messageSet =
TestMessageSet.ParseFrom(data, extensionRegistry);
Assert.AreEqual(123, messageSet.GetExtension(TestMessageSetExtension1.MessageSetExtension).I);
Assert.AreEqual("foo", messageSet.GetExtension(TestMessageSetExtension2.MessageSetExtension).Str);
// Check for unknown field with type LENGTH_DELIMITED,
// number UNKNOWN_TYPE_ID, and contents "bar".
UnknownFieldSet unknownFields = messageSet.UnknownFields;
Assert.AreEqual(1, unknownFields.FieldDictionary.Count);
Assert.IsTrue(unknownFields.HasField(UnknownTypeId));
UnknownField field = unknownFields[UnknownTypeId];
Assert.AreEqual(1, field.LengthDelimitedList.Count);
Assert.AreEqual("bar", field.LengthDelimitedList[0].ToStringUtf8());
}
}
}

@ -1,274 +0,0 @@
#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.Collections;
using System.Collections.Generic;
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers
{
/// <summary>
/// Implementation of the non-generic IMessage interface as far as possible.
/// </summary>
public abstract partial class AbstractBuilder<TMessage, TBuilder> : AbstractBuilderLite<TMessage, TBuilder>,
IBuilder<TMessage, TBuilder>
where TMessage : AbstractMessage<TMessage, TBuilder>
where TBuilder : AbstractBuilder<TMessage, TBuilder>
{
#region Unimplemented members of IBuilder
public abstract UnknownFieldSet UnknownFields { get; set; }
public abstract IDictionary<FieldDescriptor, object> AllFields { get; }
public abstract object this[FieldDescriptor field] { get; set; }
public abstract MessageDescriptor DescriptorForType { get; }
public abstract int GetRepeatedFieldCount(FieldDescriptor field);
public abstract object this[FieldDescriptor field, int index] { get; set; }
public abstract bool HasField(FieldDescriptor field);
public abstract bool HasOneof(OneofDescriptor oneof);
public abstract FieldDescriptor OneofFieldDescriptor(OneofDescriptor oneof);
public abstract IBuilder CreateBuilderForField(FieldDescriptor field);
public abstract TBuilder ClearField(FieldDescriptor field);
public abstract TBuilder ClearOneof(OneofDescriptor oneof);
public abstract TBuilder AddRepeatedField(FieldDescriptor field, object value);
#endregion
public TBuilder SetUnknownFields(UnknownFieldSet fields)
{
UnknownFields = fields;
return ThisBuilder;
}
public override TBuilder Clear()
{
foreach (FieldDescriptor field in AllFields.Keys)
{
ClearField(field);
}
return ThisBuilder;
}
public override sealed TBuilder MergeFrom(IMessageLite other)
{
if (other is IMessage)
{
return MergeFrom((IMessage) other);
}
throw new ArgumentException("MergeFrom(Message) can only merge messages of the same type.");
}
/// <summary>
/// Merge the specified other message into the message being
/// built. Merging occurs as follows. For each field:
/// For singular primitive fields, if the field is set in <paramref name="other"/>,
/// then <paramref name="other"/>'s value overwrites the value in this message.
/// For singular message fields, if the field is set in <paramref name="other"/>,
/// it is merged into the corresponding sub-message of this message using the same
/// merging rules.
/// For repeated fields, the elements in <paramref name="other"/> are concatenated
/// with the elements in this message.
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public abstract TBuilder MergeFrom(TMessage other);
public virtual TBuilder MergeFrom(IMessage other)
{
if (other.DescriptorForType != DescriptorForType)
{
throw new ArgumentException("MergeFrom(IMessage) can only merge messages of the same type.");
}
// Note: We don't attempt to verify that other's fields have valid
// types. Doing so would be a losing battle. We'd have to verify
// all sub-messages as well, and we'd have to make copies of all of
// them to insure that they don't change after verification (since
// the Message interface itself cannot enforce immutability of
// implementations).
// TODO(jonskeet): Provide a function somewhere called MakeDeepCopy()
// which allows people to make secure deep copies of messages.
foreach (KeyValuePair<FieldDescriptor, object> entry in other.AllFields)
{
FieldDescriptor field = entry.Key;
if (field.IsRepeated)
{
// Concatenate repeated fields
foreach (object element in (IEnumerable) entry.Value)
{
AddRepeatedField(field, element);
}
}
else if (field.MappedType == MappedType.Message)
{
// Merge singular messages
IMessageLite existingValue = (IMessageLite) this[field];
if (existingValue == existingValue.WeakDefaultInstanceForType)
{
this[field] = entry.Value;
}
else
{
this[field] = existingValue.WeakCreateBuilderForType()
.WeakMergeFrom(existingValue)
.WeakMergeFrom((IMessageLite) entry.Value)
.WeakBuild();
}
}
else
{
// Overwrite simple values
this[field] = entry.Value;
}
}
//Fix for unknown fields not merging, see java's AbstractMessage.Builder<T> line 236
MergeUnknownFields(other.UnknownFields);
return ThisBuilder;
}
public override TBuilder MergeFrom(ICodedInputStream input, ExtensionRegistry extensionRegistry)
{
UnknownFieldSet.Builder unknownFields = UnknownFieldSet.CreateBuilder(UnknownFields);
unknownFields.MergeFrom(input, extensionRegistry, this);
UnknownFields = unknownFields.Build();
return ThisBuilder;
}
public virtual TBuilder MergeUnknownFields(UnknownFieldSet unknownFields)
{
UnknownFields = UnknownFieldSet.CreateBuilder(UnknownFields)
.MergeFrom(unknownFields)
.Build();
return ThisBuilder;
}
public virtual IBuilder SetField(FieldDescriptor field, object value)
{
this[field] = value;
return ThisBuilder;
}
public virtual IBuilder SetRepeatedField(FieldDescriptor field, int index, object value)
{
this[field, index] = value;
return ThisBuilder;
}
#region Explicit Implementations
IMessage IBuilder.WeakBuild()
{
return Build();
}
IBuilder IBuilder.WeakAddRepeatedField(FieldDescriptor field, object value)
{
return AddRepeatedField(field, value);
}
IBuilder IBuilder.WeakClear()
{
return Clear();
}
IBuilder IBuilder.WeakMergeFrom(IMessage message)
{
return MergeFrom(message);
}
IBuilder IBuilder.WeakMergeFrom(ICodedInputStream input)
{
return MergeFrom(input);
}
IBuilder IBuilder.WeakMergeFrom(ICodedInputStream input, ExtensionRegistry registry)
{
return MergeFrom(input, registry);
}
IBuilder IBuilder.WeakMergeFrom(ByteString data)
{
return MergeFrom(data);
}
IBuilder IBuilder.WeakMergeFrom(ByteString data, ExtensionRegistry registry)
{
return MergeFrom(data, registry);
}
IMessage IBuilder.WeakBuildPartial()
{
return BuildPartial();
}
IBuilder IBuilder.WeakClone()
{
return Clone();
}
IMessage IBuilder.WeakDefaultInstanceForType
{
get { return DefaultInstanceForType; }
}
IBuilder IBuilder.WeakClearField(FieldDescriptor field)
{
return ClearField(field);
}
IBuilder IBuilder.WeakClearOneof(OneofDescriptor oneof)
{
return ClearOneof(oneof);
}
#endregion
/// <summary>
/// Converts this builder to a string using <see cref="TextFormat" />.
/// </summary>
/// <remarks>
/// This method is not sealed (in the way that it is in <see cref="AbstractMessage{TMessage, TBuilder}" />
/// as it was added after earlier releases; some other implementations may already be overriding the
/// method.
/// </remarks>
public override string ToString()
{
return TextFormat.PrintToString(this);
}
}
}

@ -1,264 +0,0 @@
#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;
namespace Google.ProtocolBuffers
{
/// <summary>
/// Implementation of the non-generic IMessage interface as far as possible.
/// </summary>
public abstract partial class AbstractBuilderLite<TMessage, TBuilder> : IBuilderLite<TMessage, TBuilder>
where TMessage : AbstractMessageLite<TMessage, TBuilder>
where TBuilder : AbstractBuilderLite<TMessage, TBuilder>
{
protected abstract TBuilder ThisBuilder { get; }
public abstract bool IsInitialized { get; }
public abstract TBuilder Clear();
public abstract TBuilder Clone();
public abstract TMessage Build();
public abstract TMessage BuildPartial();
public abstract TBuilder MergeFrom(IMessageLite other);
public abstract TBuilder MergeFrom(ICodedInputStream input, ExtensionRegistry extensionRegistry);
public abstract TMessage DefaultInstanceForType { get; }
#region IBuilderLite<TMessage,TBuilder> Members
public virtual TBuilder MergeFrom(ICodedInputStream input)
{
return MergeFrom(input, ExtensionRegistry.CreateInstance());
}
public TBuilder MergeDelimitedFrom(Stream input)
{
return MergeDelimitedFrom(input, ExtensionRegistry.CreateInstance());
}
public TBuilder MergeDelimitedFrom(Stream input, ExtensionRegistry extensionRegistry)
{
int size = (int) CodedInputStream.ReadRawVarint32(input);
Stream limitedStream = new LimitedInputStream(input, size);
return MergeFrom(limitedStream, extensionRegistry);
}
public TBuilder MergeFrom(ByteString data)
{
return MergeFrom(data, ExtensionRegistry.CreateInstance());
}
public TBuilder MergeFrom(ByteString data, ExtensionRegistry extensionRegistry)
{
CodedInputStream input = data.CreateCodedInput();
MergeFrom(input, extensionRegistry);
input.CheckLastTagWas(0);
return ThisBuilder;
}
public TBuilder MergeFrom(byte[] data)
{
CodedInputStream input = CodedInputStream.CreateInstance(data);
MergeFrom(input);
input.CheckLastTagWas(0);
return ThisBuilder;
}
public TBuilder MergeFrom(byte[] data, ExtensionRegistry extensionRegistry)
{
CodedInputStream input = CodedInputStream.CreateInstance(data);
MergeFrom(input, extensionRegistry);
input.CheckLastTagWas(0);
return ThisBuilder;
}
public TBuilder MergeFrom(Stream input)
{
CodedInputStream codedInput = CodedInputStream.CreateInstance(input);
MergeFrom(codedInput);
codedInput.CheckLastTagWas(0);
return ThisBuilder;
}
public TBuilder MergeFrom(Stream input, ExtensionRegistry extensionRegistry)
{
CodedInputStream codedInput = CodedInputStream.CreateInstance(input);
MergeFrom(codedInput, extensionRegistry);
codedInput.CheckLastTagWas(0);
return ThisBuilder;
}
#endregion
#region Explicit definitions
IBuilderLite IBuilderLite.WeakClear()
{
return Clear();
}
IBuilderLite IBuilderLite.WeakMergeFrom(IMessageLite message)
{
return MergeFrom(message);
}
IBuilderLite IBuilderLite.WeakMergeFrom(ByteString data)
{
return MergeFrom(data);
}
IBuilderLite IBuilderLite.WeakMergeFrom(ByteString data, ExtensionRegistry registry)
{
return MergeFrom(data, registry);
}
IBuilderLite IBuilderLite.WeakMergeFrom(ICodedInputStream input)
{
return MergeFrom(input);
}
IBuilderLite IBuilderLite.WeakMergeFrom(ICodedInputStream input, ExtensionRegistry registry)
{
return MergeFrom(input, registry);
}
IMessageLite IBuilderLite.WeakBuild()
{
return Build();
}
IMessageLite IBuilderLite.WeakBuildPartial()
{
return BuildPartial();
}
IBuilderLite IBuilderLite.WeakClone()
{
return Clone();
}
IMessageLite IBuilderLite.WeakDefaultInstanceForType
{
get { return DefaultInstanceForType; }
}
#endregion
#region LimitedInputStream
/// <summary>
/// Stream implementation which proxies another stream, only allowing a certain amount
/// of data to be read. Note that this is only used to read delimited streams, so it
/// doesn't attempt to implement everything.
/// </summary>
private class LimitedInputStream : Stream
{
private readonly Stream proxied;
private int bytesLeft;
internal LimitedInputStream(Stream proxied, int size)
{
this.proxied = proxied;
bytesLeft = size;
}
public override bool CanRead
{
get { return true; }
}
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return false; }
}
public override void Flush()
{
}
public override long Length
{
get { throw new NotSupportedException(); }
}
public override long Position
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
public override int Read(byte[] buffer, int offset, int count)
{
if (bytesLeft > 0)
{
int bytesRead = proxied.Read(buffer, offset, Math.Min(bytesLeft, count));
bytesLeft -= bytesRead;
return bytesRead;
}
return 0;
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
}
#endregion
}
}

@ -1,293 +0,0 @@
#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.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Google.ProtocolBuffers.Collections;
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers
{
/// <summary>
/// Implementation of the non-generic IMessage interface as far as possible.
/// </summary>
public abstract partial class AbstractMessage<TMessage, TBuilder> : AbstractMessageLite<TMessage, TBuilder>,
IMessage<TMessage, TBuilder>
where TMessage : AbstractMessage<TMessage, TBuilder>
where TBuilder : AbstractBuilder<TMessage, TBuilder>
{
/// <summary>
/// The serialized size if it's already been computed, or null
/// if we haven't computed it yet.
/// </summary>
private int? memoizedSize = null;
#region Unimplemented members of IMessage
public abstract MessageDescriptor DescriptorForType { get; }
public abstract IDictionary<FieldDescriptor, object> AllFields { get; }
public abstract bool HasField(FieldDescriptor field);
public abstract bool HasOneof(OneofDescriptor oneof);
public abstract FieldDescriptor OneofFieldDescriptor(OneofDescriptor oneof);
public abstract object this[FieldDescriptor field] { get; }
public abstract int GetRepeatedFieldCount(FieldDescriptor field);
public abstract object this[FieldDescriptor field, int index] { get; }
public abstract UnknownFieldSet UnknownFields { get; }
#endregion
/// <summary>
/// Returns true iff all required fields in the message and all embedded
/// messages are set.
/// </summary>
public override bool IsInitialized
{
get
{
// Check that all required fields are present.
foreach (FieldDescriptor field in DescriptorForType.Fields)
{
if (field.IsRequired && !HasField(field))
{
return false;
}
}
// Check that embedded messages are initialized.
foreach (KeyValuePair<FieldDescriptor, object> entry in AllFields)
{
FieldDescriptor field = entry.Key;
if (field.MappedType == MappedType.Message)
{
if (field.IsRepeated)
{
// We know it's an IList<T>, but not the exact type - so
// IEnumerable is the best we can do. (C# generics aren't covariant yet.)
foreach (IMessageLite element in (IEnumerable) entry.Value)
{
if (!element.IsInitialized)
{
return false;
}
}
}
else
{
if (!((IMessageLite) entry.Value).IsInitialized)
{
return false;
}
}
}
}
return true;
}
}
public override sealed string ToString()
{
return TextFormat.PrintToString(this);
}
public override sealed void PrintTo(TextWriter writer)
{
TextFormat.Print(this, writer);
}
/// <summary>
/// Serializes the message and writes it to the given output stream.
/// This does not flush or close the stream.
/// </summary>
/// <remarks>
/// Protocol Buffers are not self-delimiting. Therefore, if you write
/// any more data to the stream after the message, you must somehow ensure
/// that the parser on the receiving end does not interpret this as being
/// part of the protocol message. One way of doing this is by writing the size
/// of the message before the data, then making sure you limit the input to
/// that size when receiving the data. Alternatively, use WriteDelimitedTo(Stream).
/// </remarks>
public override void WriteTo(ICodedOutputStream output)
{
foreach (KeyValuePair<FieldDescriptor, object> entry in AllFields)
{
FieldDescriptor field = entry.Key;
if (field.IsRepeated)
{
// We know it's an IList<T>, but not the exact type - so
// IEnumerable is the best we can do. (C# generics aren't covariant yet.)
IEnumerable valueList = (IEnumerable) entry.Value;
if (field.IsPacked)
{
output.WritePackedArray(field.FieldType, field.FieldNumber, field.Name, valueList);
}
else
{
output.WriteArray(field.FieldType, field.FieldNumber, field.Name, valueList);
}
}
else
{
output.WriteField(field.FieldType, field.FieldNumber, field.Name, entry.Value);
}
}
UnknownFieldSet unknownFields = UnknownFields;
if (DescriptorForType.Options.MessageSetWireFormat)
{
unknownFields.WriteAsMessageSetTo(output);
}
else
{
unknownFields.WriteTo(output);
}
}
/// <summary>
/// Returns the number of bytes required to encode this message.
/// The result is only computed on the first call and memoized after that.
/// </summary>
public override int SerializedSize
{
get
{
if (memoizedSize != null)
{
return memoizedSize.Value;
}
int size = 0;
foreach (KeyValuePair<FieldDescriptor, object> entry in AllFields)
{
FieldDescriptor field = entry.Key;
if (field.IsRepeated)
{
IEnumerable valueList = (IEnumerable) entry.Value;
if (field.IsPacked)
{
int dataSize = 0;
foreach (object element in valueList)
{
dataSize += CodedOutputStream.ComputeFieldSizeNoTag(field.FieldType, element);
}
size += dataSize;
size += CodedOutputStream.ComputeTagSize(field.FieldNumber);
size += CodedOutputStream.ComputeRawVarint32Size((uint) dataSize);
}
else
{
foreach (object element in valueList)
{
size += CodedOutputStream.ComputeFieldSize(field.FieldType, field.FieldNumber, element);
}
}
}
else
{
size += CodedOutputStream.ComputeFieldSize(field.FieldType, field.FieldNumber, entry.Value);
}
}
UnknownFieldSet unknownFields = UnknownFields;
if (DescriptorForType.Options.MessageSetWireFormat)
{
size += unknownFields.SerializedSizeAsMessageSet;
}
else
{
size += unknownFields.SerializedSize;
}
memoizedSize = size;
return size;
}
}
/// <summary>
/// Compares the specified object with this message for equality.
/// Returns true iff the given object is a message of the same type
/// (as defined by DescriptorForType) and has identical values
/// for all its fields.
/// </summary>
public override bool Equals(object other)
{
if (other == this)
{
return true;
}
IMessage otherMessage = other as IMessage;
if (otherMessage == null || otherMessage.DescriptorForType != DescriptorForType)
{
return false;
}
return Dictionaries.Equals(AllFields, otherMessage.AllFields) &&
UnknownFields.Equals(otherMessage.UnknownFields);
}
/// <summary>
/// Returns the hash code value for this message.
/// TODO(jonskeet): Specify the hash algorithm, but better than the Java one!
/// </summary>
public override int GetHashCode()
{
int hash = 41;
hash = (19*hash) + DescriptorForType.GetHashCode();
hash = (53*hash) + Dictionaries.GetHashCode(AllFields);
hash = (29*hash) + UnknownFields.GetHashCode();
return hash;
}
#region Explicit Members
IBuilder IMessage.WeakCreateBuilderForType()
{
return CreateBuilderForType();
}
IBuilder IMessage.WeakToBuilder()
{
return ToBuilder();
}
IMessage IMessage.WeakDefaultInstanceForType
{
get { return DefaultInstanceForType; }
}
#endregion
}
}

@ -1,140 +0,0 @@
#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.IO;
namespace Google.ProtocolBuffers
{
/// <summary>
/// Implementation of the non-generic IMessage interface as far as possible.
/// </summary>
public abstract partial class AbstractMessageLite<TMessage, TBuilder> : IMessageLite<TMessage, TBuilder>
where TMessage : AbstractMessageLite<TMessage, TBuilder>
where TBuilder : AbstractBuilderLite<TMessage, TBuilder>
{
public abstract TBuilder CreateBuilderForType();
public abstract TBuilder ToBuilder();
public abstract TMessage DefaultInstanceForType { get; }
public abstract bool IsInitialized { get; }
public abstract void WriteTo(ICodedOutputStream output);
public abstract int SerializedSize { get; }
//public override bool Equals(object other) {
//}
//public override int GetHashCode() {
//}
public abstract void PrintTo(TextWriter writer);
#region IMessageLite<TMessage,TBuilder> Members
/// <summary>
/// Serializes the message to a ByteString. This is a trivial wrapper
/// around WriteTo(ICodedOutputStream).
/// </summary>
public ByteString ToByteString()
{
ByteString.CodedBuilder output = new ByteString.CodedBuilder(SerializedSize);
WriteTo(output.CodedOutput);
return output.Build();
}
/// <summary>
/// Serializes the message to a byte array. This is a trivial wrapper
/// around WriteTo(ICodedOutputStream).
/// </summary>
public byte[] ToByteArray()
{
byte[] result = new byte[SerializedSize];
CodedOutputStream output = CodedOutputStream.CreateInstance(result);
WriteTo(output);
output.CheckNoSpaceLeft();
return result;
}
/// <summary>
/// Serializes the message and writes it to the given stream.
/// This is just a wrapper around WriteTo(CodedOutputStream). This
/// does not flush or close the stream.
/// </summary>
/// <param name="output"></param>
public void WriteTo(Stream output)
{
CodedOutputStream codedOutput = CodedOutputStream.CreateInstance(output);
WriteTo(codedOutput);
codedOutput.Flush();
}
/// <summary>
/// Like WriteTo(Stream) but writes the size of the message as a varint before
/// writing the data. This allows more data to be written to the stream after the
/// message without the need to delimit the message data yourself. Use
/// IBuilder.MergeDelimitedFrom(Stream) or the static method
/// YourMessageType.ParseDelimitedFrom(Stream) to parse messages written by this method.
/// </summary>
/// <param name="output"></param>
public void WriteDelimitedTo(Stream output)
{
CodedOutputStream codedOutput = CodedOutputStream.CreateInstance(output);
codedOutput.WriteRawVarint32((uint) SerializedSize);
WriteTo(codedOutput);
codedOutput.Flush();
}
IBuilderLite IMessageLite.WeakCreateBuilderForType()
{
return CreateBuilderForType();
}
IBuilderLite IMessageLite.WeakToBuilder()
{
return ToBuilder();
}
IMessageLite IMessageLite.WeakDefaultInstanceForType
{
get { return DefaultInstanceForType; }
}
#endregion
}
}

@ -36,7 +36,7 @@
using System;
namespace Google.ProtocolBuffers
namespace Google.Protobuf
{
/// <summary>
/// Provides a utility routine to copy small arrays much more quickly than Buffer.BlockCopy

@ -40,7 +40,7 @@ using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Google.ProtocolBuffers
namespace Google.Protobuf
{
/// <summary>
/// Immutable array of bytes.
@ -208,6 +208,24 @@ namespace Google.ProtocolBuffers
return CodedInputStream.CreateInstance(bytes);
}
public static bool operator ==(ByteString lhs, ByteString rhs)
{
if (ReferenceEquals(lhs, rhs))
{
return true;
}
if (ReferenceEquals(lhs, null))
{
return false;
}
return lhs.Equals(rhs);
}
public static bool operator !=(ByteString lhs, ByteString rhs)
{
return !(lhs == rhs);
}
// TODO(jonskeet): CopyTo if it turns out to be required
public override bool Equals(object obj)

@ -38,9 +38,9 @@ using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Google.ProtocolBuffers.Descriptors;
using Google.Protobuf.Descriptors;
namespace Google.ProtocolBuffers
namespace Google.Protobuf
{
/// <summary>
/// Readings and decodes protocol message fields.
@ -367,32 +367,14 @@ namespace Google.ProtocolBuffers
/// <summary>
/// Reads a group field value from the stream.
/// </summary>
public void ReadGroup(int fieldNumber, IBuilderLite builder,
ExtensionRegistry extensionRegistry)
public void ReadGroup(int fieldNumber, IMessage message)
{
if (recursionDepth >= recursionLimit)
{
throw InvalidProtocolBufferException.RecursionLimitExceeded();
}
++recursionDepth;
builder.WeakMergeFrom(this, extensionRegistry);
CheckLastTagWas(WireFormat.MakeTag(fieldNumber, WireFormat.WireType.EndGroup));
--recursionDepth;
}
/// <summary>
/// Reads a group field value from the stream and merges it into the given
/// UnknownFieldSet.
/// </summary>
[Obsolete]
public void ReadUnknownGroup(int fieldNumber, IBuilderLite builder)
{
if (recursionDepth >= recursionLimit)
{
throw InvalidProtocolBufferException.RecursionLimitExceeded();
}
++recursionDepth;
builder.WeakMergeFrom(this);
message.MergeFrom(this);
CheckLastTagWas(WireFormat.MakeTag(fieldNumber, WireFormat.WireType.EndGroup));
--recursionDepth;
}
@ -400,7 +382,7 @@ namespace Google.ProtocolBuffers
/// <summary>
/// Reads an embedded message field value from the stream.
/// </summary>
public void ReadMessage(IBuilderLite builder, ExtensionRegistry extensionRegistry)
public void ReadMessage(IMessage builder)
{
int length = (int) ReadRawVarint32();
if (recursionDepth >= recursionLimit)
@ -409,7 +391,7 @@ namespace Google.ProtocolBuffers
}
int oldLimit = PushLimit(length);
++recursionDepth;
builder.WeakMergeFrom(this, extensionRegistry);
builder.MergeFrom(this);
CheckLastTagWas(0);
--recursionDepth;
PopLimit(oldLimit);
@ -447,40 +429,17 @@ namespace Google.ProtocolBuffers
return true;
}
/// <summary>
/// Reads an enum field value from the stream. The caller is responsible
/// for converting the numeric value to an actual enum.
/// </summary>
public bool ReadEnum(ref IEnumLite value, out object unknown, IEnumLiteMap mapping)
{
int rawValue = (int) ReadRawVarint32();
value = mapping.FindValueByNumber(rawValue);
if (value != null)
{
unknown = null;
return true;
}
unknown = rawValue;
return false;
}
/// <summary>
/// Reads an enum field value from the stream. If the enum is valid for type T,
/// then the ref value is set and it returns true. Otherwise the unknown output
/// value is set and this method returns false.
/// </summary>
public bool ReadEnum<T>(ref T value, out object unknown)
public bool ReadEnum<T>(ref T value)
where T : struct, IComparable, IFormattable
{
int number = (int) ReadRawVarint32();
if (EnumParser<T>.TryConvert(number, ref value))
{
unknown = null;
return true;
}
unknown = number;
return false;
value = EnumHelper<T>.FromInt32(number);
return true;
}
/// <summary>
@ -655,6 +614,7 @@ namespace Google.ProtocolBuffers
public void ReadInt32Array(uint fieldTag, string fieldName, ICollection<int> list)
{
// TODO(jonskeet): Work out how this works for non-packed values. (It doesn't look like it does...)
bool isPacked;
int holdLimit;
if (BeginArray(fieldTag, out isPacked, out holdLimit))
@ -833,62 +793,9 @@ namespace Google.ProtocolBuffers
}
}
public void ReadEnumArray(uint fieldTag, string fieldName, ICollection<IEnumLite> list,
out ICollection<object> unknown, IEnumLiteMap mapping)
{
unknown = null;
object unkval;
IEnumLite value = null;
WireFormat.WireType wformat = WireFormat.GetTagWireType(fieldTag);
// 2.3 allows packed form even if the field is not declared packed.
if (wformat == WireFormat.WireType.LengthDelimited)
{
int length = (int) (ReadRawVarint32() & int.MaxValue);
int limit = PushLimit(length);
while (!ReachedLimit)
{
if (ReadEnum(ref value, out unkval, mapping))
{
list.Add(value);
}
else
{
if (unknown == null)
{
unknown = new List<object>();
}
unknown.Add(unkval);
}
}
PopLimit(limit);
}
else
{
do
{
if (ReadEnum(ref value, out unkval, mapping))
{
list.Add(value);
}
else
{
if (unknown == null)
{
unknown = new List<object>();
}
unknown.Add(unkval);
}
} while (ContinueArray(fieldTag));
}
}
public void ReadEnumArray<T>(uint fieldTag, string fieldName, ICollection<T> list,
out ICollection<object> unknown)
public void ReadEnumArray<T>(uint fieldTag, string fieldName, ICollection<T> list)
where T : struct, IComparable, IFormattable
{
unknown = null;
object unkval;
T value = default(T);
WireFormat.WireType wformat = WireFormat.GetTagWireType(fieldTag);
@ -899,18 +806,8 @@ namespace Google.ProtocolBuffers
int limit = PushLimit(length);
while (!ReachedLimit)
{
if (ReadEnum<T>(ref value, out unkval))
{
list.Add(value);
}
else
{
if (unknown == null)
{
unknown = new List<object>();
}
unknown.Add(unkval);
}
ReadEnum<T>(ref value);
list.Add(value);
}
PopLimit(limit);
}
@ -918,41 +815,31 @@ namespace Google.ProtocolBuffers
{
do
{
if (ReadEnum(ref value, out unkval))
{
list.Add(value);
}
else
{
if (unknown == null)
{
unknown = new List<object>();
}
unknown.Add(unkval);
}
ReadEnum(ref value);
list.Add(value);
} while (ContinueArray(fieldTag));
}
}
public void ReadMessageArray<T>(uint fieldTag, string fieldName, ICollection<T> list, T messageType,
ExtensionRegistry registry) where T : IMessageLite
public void ReadMessageArray<T>(uint fieldTag, string fieldName, ICollection<T> list, MessageParser<T> messageParser)
where T : IMessage<T>
{
do
{
IBuilderLite builder = messageType.WeakCreateBuilderForType();
ReadMessage(builder, registry);
list.Add((T) builder.WeakBuildPartial());
T message = messageParser.CreateTemplate();
ReadMessage(message);
list.Add(message);
} while (ContinueArray(fieldTag));
}
public void ReadGroupArray<T>(uint fieldTag, string fieldName, ICollection<T> list, T messageType,
ExtensionRegistry registry) where T : IMessageLite
public void ReadGroupArray<T>(uint fieldTag, string fieldName, ICollection<T> list, MessageParser<T> messageParser)
where T : IMessage<T>
{
do
{
IBuilderLite builder = messageType.WeakCreateBuilderForType();
ReadGroup(WireFormat.GetTagFieldNumber(fieldTag), builder, registry);
list.Add((T) builder.WeakBuildPartial());
T message = messageParser.CreateTemplate();
ReadGroup(WireFormat.GetTagFieldNumber(fieldTag), message);
list.Add(message);
} while (ContinueArray(fieldTag));
}

@ -37,9 +37,9 @@
using System;
using System.Globalization;
using System.Text;
using Google.ProtocolBuffers.Descriptors;
using Google.Protobuf.Descriptors;
namespace Google.ProtocolBuffers
namespace Google.Protobuf
{
// This part of CodedOutputStream provides all the static entry points that are used
// by generated code and internally to compute the size of messages prior to being
@ -145,9 +145,9 @@ namespace Google.ProtocolBuffers
/// Compute the number of bytes that would be needed to encode a
/// group field, including the tag.
/// </summary>
public static int ComputeGroupSize(int fieldNumber, IMessageLite value)
public static int ComputeGroupSize(int fieldNumber, IMessage value)
{
return ComputeTagSize(fieldNumber)*2 + value.SerializedSize;
return ComputeTagSize(fieldNumber)*2 + value.CalculateSize();
}
/// <summary>
@ -156,18 +156,18 @@ namespace Google.ProtocolBuffers
/// </summary>
[Obsolete]
public static int ComputeUnknownGroupSize(int fieldNumber,
IMessageLite value)
IMessage value)
{
return ComputeTagSize(fieldNumber)*2 + value.SerializedSize;
return ComputeTagSize(fieldNumber)*2 + value.CalculateSize();
}
/// <summary>
/// Compute the number of bytes that would be needed to encode an
/// embedded message field, including the tag.
/// </summary>
public static int ComputeMessageSize(int fieldNumber, IMessageLite value)
public static int ComputeMessageSize(int fieldNumber, IMessage value)
{
int size = value.SerializedSize;
int size = value.CalculateSize();
return ComputeTagSize(fieldNumber) + ComputeRawVarint32Size((uint) size) + size;
}
@ -196,7 +196,7 @@ namespace Google.ProtocolBuffers
/// enum field, including the tag. The caller is responsible for
/// converting the enum value to its numeric value.
/// </summary>
public static int ComputeEnumSize(int fieldNumber, int value)
public static int ComputeEnumSize<T>(int fieldNumber, T value) where T : struct, IComparable, IFormattable
{
return ComputeTagSize(fieldNumber) + ComputeEnumSizeNoTag(value);
}
@ -332,28 +332,18 @@ namespace Google.ProtocolBuffers
/// Compute the number of bytes that would be needed to encode a
/// group field, including the tag.
/// </summary>
public static int ComputeGroupSizeNoTag(IMessageLite value)
public static int ComputeGroupSizeNoTag(IMessage value)
{
return value.SerializedSize;
}
/// <summary>
/// Compute the number of bytes that would be needed to encode a
/// group field represented by an UnknownFieldSet, including the tag.
/// </summary>
[Obsolete]
public static int ComputeUnknownGroupSizeNoTag(IMessageLite value)
{
return value.SerializedSize;
return value.CalculateSize();
}
/// <summary>
/// Compute the number of bytes that would be needed to encode an
/// embedded message field, including the tag.
/// </summary>
public static int ComputeMessageSizeNoTag(IMessageLite value)
public static int ComputeMessageSizeNoTag(IMessage value)
{
int size = value.SerializedSize;
int size = value.CalculateSize();
return ComputeRawVarint32Size((uint) size) + size;
}
@ -381,9 +371,10 @@ namespace Google.ProtocolBuffers
/// enum field, including the tag. The caller is responsible for
/// converting the enum value to its numeric value.
/// </summary>
public static int ComputeEnumSizeNoTag(int value)
public static int ComputeEnumSizeNoTag<T>(T value) where T : struct, IComparable, IFormattable
{
return ComputeInt32SizeNoTag(value);
int serializedValue = EnumHelper<T>.ToInt32(value);
return ComputeInt32SizeNoTag(serializedValue);
}
/// <summary>
@ -433,7 +424,7 @@ namespace Google.ProtocolBuffers
/// MessageSet extension to the stream. For historical reasons,
/// the wire format differs from normal fields.
/// </summary>
public static int ComputeMessageSetExtensionSize(int fieldNumber, IMessageLite value)
public static int ComputeMessageSetExtensionSize(int fieldNumber, IMessage value)
{
return ComputeTagSize(WireFormat.MessageSetField.Item)*2 +
ComputeUInt32Size(WireFormat.MessageSetField.TypeID, (uint) fieldNumber) +
@ -524,6 +515,7 @@ namespace Google.ProtocolBuffers
/// Compute the number of bytes that would be needed to encode a
/// field of arbitrary type, including the tag, to the stream.
/// </summary>
// TODO(jonskeet): Why do we need this?
public static int ComputeFieldSize(FieldType fieldType, int fieldNumber, Object value)
{
switch (fieldType)
@ -547,9 +539,9 @@ namespace Google.ProtocolBuffers
case FieldType.String:
return ComputeStringSize(fieldNumber, (string) value);
case FieldType.Group:
return ComputeGroupSize(fieldNumber, (IMessageLite) value);
return ComputeGroupSize(fieldNumber, (IMessage) value);
case FieldType.Message:
return ComputeMessageSize(fieldNumber, (IMessageLite) value);
return ComputeMessageSize(fieldNumber, (IMessage) value);
case FieldType.Bytes:
return ComputeBytesSize(fieldNumber, (ByteString) value);
case FieldType.UInt32:
@ -563,14 +555,7 @@ namespace Google.ProtocolBuffers
case FieldType.SInt64:
return ComputeSInt64Size(fieldNumber, (long) value);
case FieldType.Enum:
if (value is Enum)
{
return ComputeEnumSize(fieldNumber, Convert.ToInt32(value));
}
else
{
return ComputeEnumSize(fieldNumber, ((IEnumLite) value).Number);
}
return ComputeEnumSize(fieldNumber, Convert.ToInt64(value));
default:
throw new ArgumentOutOfRangeException("Invalid field type " + fieldType);
}
@ -580,6 +565,7 @@ namespace Google.ProtocolBuffers
/// Compute the number of bytes that would be needed to encode a
/// field of arbitrary type, excluding the tag, to the stream.
/// </summary>
// TODO(jonskeet): Why do we need this?
public static int ComputeFieldSizeNoTag(FieldType fieldType, Object value)
{
switch (fieldType)
@ -603,9 +589,9 @@ namespace Google.ProtocolBuffers
case FieldType.String:
return ComputeStringSizeNoTag((string) value);
case FieldType.Group:
return ComputeGroupSizeNoTag((IMessageLite) value);
return ComputeGroupSizeNoTag((IMessage) value);
case FieldType.Message:
return ComputeMessageSizeNoTag((IMessageLite) value);
return ComputeMessageSizeNoTag((IMessage) value);
case FieldType.Bytes:
return ComputeBytesSizeNoTag((ByteString) value);
case FieldType.UInt32:
@ -619,14 +605,7 @@ namespace Google.ProtocolBuffers
case FieldType.SInt64:
return ComputeSInt64SizeNoTag((long) value);
case FieldType.Enum:
if (value is Enum)
{
return ComputeEnumSizeNoTag(Convert.ToInt32(value));
}
else
{
return ComputeEnumSizeNoTag(((IEnumLite) value).Number);
}
return ComputeEnumSizeNoTag(Convert.ToInt64(value));
default:
throw new ArgumentOutOfRangeException("Invalid field type " + fieldType);
}

@ -36,13 +36,12 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Google.ProtocolBuffers.Collections;
using Google.ProtocolBuffers.Descriptors;
using Google.Protobuf.Collections;
using Google.Protobuf.Descriptors;
namespace Google.ProtocolBuffers
namespace Google.Protobuf
{
/// <summary>
/// Encodes and writes protocol message fields.
@ -144,45 +143,9 @@ namespace Google.ProtocolBuffers
void ICodedOutputStream.WriteMessageStart() { }
void ICodedOutputStream.WriteMessageEnd() { Flush(); }
#region Writing of unknown fields
[Obsolete]
public void WriteUnknownGroup(int fieldNumber, IMessageLite value)
{
WriteTag(fieldNumber, WireFormat.WireType.StartGroup);
value.WriteTo(this);
WriteTag(fieldNumber, WireFormat.WireType.EndGroup);
}
public void WriteUnknownBytes(int fieldNumber, ByteString value)
{
WriteBytes(fieldNumber, null /*not used*/, value);
}
public void WriteUnknownField(int fieldNumber, WireFormat.WireType wireType, ulong value)
{
if (wireType == WireFormat.WireType.Varint)
{
WriteUInt64(fieldNumber, null /*not used*/, value);
}
else if (wireType == WireFormat.WireType.Fixed32)
{
WriteFixed32(fieldNumber, null /*not used*/, (uint) value);
}
else if (wireType == WireFormat.WireType.Fixed64)
{
WriteFixed64(fieldNumber, null /*not used*/, value);
}
else
{
throw InvalidProtocolBufferException.InvalidWireType();
}
}
#endregion
#region Writing of tags and fields
// TODO(jonskeet): Do we need this?
public void WriteField(FieldType fieldType, int fieldNumber, string fieldName, object value)
{
switch (fieldType)
@ -191,10 +154,10 @@ namespace Google.ProtocolBuffers
WriteString(fieldNumber, fieldName, (string) value);
break;
case FieldType.Message:
WriteMessage(fieldNumber, fieldName, (IMessageLite) value);
WriteMessage(fieldNumber, fieldName, (IMessage) value);
break;
case FieldType.Group:
WriteGroup(fieldNumber, fieldName, (IMessageLite) value);
WriteGroup(fieldNumber, fieldName, (IMessage) value);
break;
case FieldType.Bytes:
WriteBytes(fieldNumber, fieldName, (ByteString) value);
@ -203,15 +166,7 @@ namespace Google.ProtocolBuffers
WriteBool(fieldNumber, fieldName, (bool) value);
break;
case FieldType.Enum:
if (value is Enum)
{
WriteEnum(fieldNumber, fieldName, (int) value, null /*not used*/);
}
else
{
WriteEnum(fieldNumber, fieldName, ((IEnumLite) value).Number, null /*not used*/);
}
break;
throw new NotImplementedException();
case FieldType.Int32:
WriteInt32(fieldNumber, fieldName, (int) value);
break;
@ -356,17 +311,17 @@ namespace Google.ProtocolBuffers
/// <summary>
/// Writes a group field value, including tag, to the stream.
/// </summary>
public void WriteGroup(int fieldNumber, string fieldName, IMessageLite value)
public void WriteGroup(int fieldNumber, string fieldName, IMessage value)
{
WriteTag(fieldNumber, WireFormat.WireType.StartGroup);
value.WriteTo(this);
WriteTag(fieldNumber, WireFormat.WireType.EndGroup);
}
public void WriteMessage(int fieldNumber, string fieldName, IMessageLite value)
public void WriteMessage(int fieldNumber, string fieldName, IMessage value)
{
WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited);
WriteRawVarint32((uint) value.SerializedSize);
WriteRawVarint32((uint) value.CalculateSize());
value.WriteTo(this);
}
@ -383,10 +338,10 @@ namespace Google.ProtocolBuffers
WriteRawVarint32(value);
}
public void WriteEnum(int fieldNumber, string fieldName, int value, object rawValue)
public void WriteEnum<T>(int fieldNumber, string fieldName, T value) where T : struct, IComparable, IFormattable
{
WriteTag(fieldNumber, WireFormat.WireType.Varint);
WriteInt32NoTag(value);
WriteInt32NoTag(EnumHelper<T>.ToInt32(value));
}
public void WriteSFixed32(int fieldNumber, string fieldName, int value)
@ -413,7 +368,7 @@ namespace Google.ProtocolBuffers
WriteRawVarint64(EncodeZigZag64(value));
}
public void WriteMessageSetExtension(int fieldNumber, string fieldName, IMessageLite value)
public void WriteMessageSetExtension(int fieldNumber, string fieldName, IMessage value)
{
WriteTag(WireFormat.MessageSetField.Item, WireFormat.WireType.StartGroup);
WriteUInt32(WireFormat.MessageSetField.TypeID, "type_id", (uint) fieldNumber);
@ -432,7 +387,7 @@ namespace Google.ProtocolBuffers
#endregion
#region Writing of values without tags
// TODO(jonskeet): Remove this?
public void WriteFieldNoTag(FieldType fieldType, object value)
{
switch (fieldType)
@ -441,10 +396,10 @@ namespace Google.ProtocolBuffers
WriteStringNoTag((string) value);
break;
case FieldType.Message:
WriteMessageNoTag((IMessageLite) value);
WriteMessageNoTag((IMessage) value);
break;
case FieldType.Group:
WriteGroupNoTag((IMessageLite) value);
WriteGroupNoTag((IMessage) value);
break;
case FieldType.Bytes:
WriteBytesNoTag((ByteString) value);
@ -453,14 +408,7 @@ namespace Google.ProtocolBuffers
WriteBoolNoTag((bool) value);
break;
case FieldType.Enum:
if (value is Enum)
{
WriteEnumNoTag((int) value);
}
else
{
WriteEnumNoTag(((IEnumLite) value).Number);
}
WriteEnumNoTag((int) value);
break;
case FieldType.Int32:
WriteInt32NoTag((int) value);
@ -613,14 +561,14 @@ namespace Google.ProtocolBuffers
/// <summary>
/// Writes a group field value, without a tag, to the stream.
/// </summary>
public void WriteGroupNoTag(IMessageLite value)
public void WriteGroupNoTag(IMessage value)
{
value.WriteTo(this);
}
public void WriteMessageNoTag(IMessageLite value)
public void WriteMessageNoTag(IMessage value)
{
WriteRawVarint32((uint) value.SerializedSize);
WriteRawVarint32((uint) value.CalculateSize());
value.WriteTo(this);
}
@ -635,9 +583,9 @@ namespace Google.ProtocolBuffers
WriteRawVarint32(value);
}
public void WriteEnumNoTag(int value)
public void WriteEnumNoTag<T>(T value) where T : struct, IComparable, IFormattable
{
WriteInt32NoTag(value);
WriteInt32NoTag(EnumHelper<T>.ToInt32(value));
}
public void WriteSFixed32NoTag(int value)
@ -664,6 +612,7 @@ namespace Google.ProtocolBuffers
#region Write array members
// TODO(jonskeet): Remove?
public void WriteArray(FieldType fieldType, int fieldNumber, string fieldName, IEnumerable list)
{
foreach (object element in list)
@ -672,25 +621,25 @@ namespace Google.ProtocolBuffers
}
}
public void WriteGroupArray<T>(int fieldNumber, string fieldName, IEnumerable<T> list)
where T : IMessageLite
public void WriteGroupArray<T>(int fieldNumber, string fieldName, RepeatedField<T> list)
where T : IMessage
{
foreach (IMessageLite value in list)
foreach (IMessage value in list)
{
WriteGroup(fieldNumber, fieldName, value);
}
}
public void WriteMessageArray<T>(int fieldNumber, string fieldName, IEnumerable<T> list)
where T : IMessageLite
public void WriteMessageArray<T>(int fieldNumber, string fieldName, RepeatedField<T> list)
where T : IMessage
{
foreach (IMessageLite value in list)
foreach (IMessage value in list)
{
WriteMessage(fieldNumber, fieldName, value);
}
}
public void WriteStringArray(int fieldNumber, string fieldName, IEnumerable<string> list)
public void WriteStringArray(int fieldNumber, string fieldName, RepeatedField<string> list)
{
foreach (var value in list)
{
@ -698,7 +647,7 @@ namespace Google.ProtocolBuffers
}
}
public void WriteBytesArray(int fieldNumber, string fieldName, IEnumerable<ByteString> list)
public void WriteBytesArray(int fieldNumber, string fieldName, RepeatedField<ByteString> list)
{
foreach (var value in list)
{
@ -706,7 +655,7 @@ namespace Google.ProtocolBuffers
}
}
public void WriteBoolArray(int fieldNumber, string fieldName, IEnumerable<bool> list)
public void WriteBoolArray(int fieldNumber, string fieldName, RepeatedField<bool> list)
{
foreach (var value in list)
{
@ -714,7 +663,7 @@ namespace Google.ProtocolBuffers
}
}
public void WriteInt32Array(int fieldNumber, string fieldName, IEnumerable<int> list)
public void WriteInt32Array(int fieldNumber, string fieldName, RepeatedField<int> list)
{
foreach (var value in list)
{
@ -722,7 +671,7 @@ namespace Google.ProtocolBuffers
}
}
public void WriteSInt32Array(int fieldNumber, string fieldName, IEnumerable<int> list)
public void WriteSInt32Array(int fieldNumber, string fieldName, RepeatedField<int> list)
{
foreach (var value in list)
{
@ -730,7 +679,7 @@ namespace Google.ProtocolBuffers
}
}
public void WriteUInt32Array(int fieldNumber, string fieldName, IEnumerable<uint> list)
public void WriteUInt32Array(int fieldNumber, string fieldName, RepeatedField<uint> list)
{
foreach (var value in list)
{
@ -738,7 +687,7 @@ namespace Google.ProtocolBuffers
}
}
public void WriteFixed32Array(int fieldNumber, string fieldName, IEnumerable<uint> list)
public void WriteFixed32Array(int fieldNumber, string fieldName, RepeatedField<uint> list)
{
foreach (var value in list)
{
@ -746,7 +695,7 @@ namespace Google.ProtocolBuffers
}
}
public void WriteSFixed32Array(int fieldNumber, string fieldName, IEnumerable<int> list)
public void WriteSFixed32Array(int fieldNumber, string fieldName, RepeatedField<int> list)
{
foreach (var value in list)
{
@ -754,7 +703,7 @@ namespace Google.ProtocolBuffers
}
}
public void WriteInt64Array(int fieldNumber, string fieldName, IEnumerable<long> list)
public void WriteInt64Array(int fieldNumber, string fieldName, RepeatedField<long> list)
{
foreach (var value in list)
{
@ -762,7 +711,7 @@ namespace Google.ProtocolBuffers
}
}
public void WriteSInt64Array(int fieldNumber, string fieldName, IEnumerable<long> list)
public void WriteSInt64Array(int fieldNumber, string fieldName, RepeatedField<long> list)
{
foreach (var value in list)
{
@ -770,7 +719,7 @@ namespace Google.ProtocolBuffers
}
}
public void WriteUInt64Array(int fieldNumber, string fieldName, IEnumerable<ulong> list)
public void WriteUInt64Array(int fieldNumber, string fieldName, RepeatedField<ulong> list)
{
foreach (var value in list)
{
@ -778,7 +727,7 @@ namespace Google.ProtocolBuffers
}
}
public void WriteFixed64Array(int fieldNumber, string fieldName, IEnumerable<ulong> list)
public void WriteFixed64Array(int fieldNumber, string fieldName, RepeatedField<ulong> list)
{
foreach (var value in list)
{
@ -786,7 +735,7 @@ namespace Google.ProtocolBuffers
}
}
public void WriteSFixed64Array(int fieldNumber, string fieldName, IEnumerable<long> list)
public void WriteSFixed64Array(int fieldNumber, string fieldName, RepeatedField<long> list)
{
foreach (var value in list)
{
@ -794,7 +743,7 @@ namespace Google.ProtocolBuffers
}
}
public void WriteDoubleArray(int fieldNumber, string fieldName, IEnumerable<double> list)
public void WriteDoubleArray(int fieldNumber, string fieldName, RepeatedField<double> list)
{
foreach (var value in list)
{
@ -802,7 +751,7 @@ namespace Google.ProtocolBuffers
}
}
public void WriteFloatArray(int fieldNumber, string fieldName, IEnumerable<float> list)
public void WriteFloatArray(int fieldNumber, string fieldName, RepeatedField<float> list)
{
foreach (var value in list)
{
@ -810,22 +759,12 @@ namespace Google.ProtocolBuffers
}
}
public void WriteEnumArray<T>(int fieldNumber, string fieldName, IEnumerable<T> list)
public void WriteEnumArray<T>(int fieldNumber, string fieldName, RepeatedField<T> list)
where T : struct, IComparable, IFormattable
{
if (list is ICastArray)
foreach (T value in list)
{
foreach (int value in ((ICastArray) list).CastArray<int>())
{
WriteEnum(fieldNumber, fieldName, value, null /*unused*/);
}
}
else
{
foreach (object value in list)
{
WriteEnum(fieldNumber, fieldName, (int) value, null /*unused*/);
}
WriteEnum(fieldNumber, fieldName, value);
}
}
@ -833,6 +772,7 @@ namespace Google.ProtocolBuffers
#region Write packed array members
// TODO(jonskeet): Remove?
public void WritePackedArray(FieldType fieldType, int fieldNumber, string fieldName, IEnumerable list)
{
int calculatedSize = 0;
@ -850,205 +790,215 @@ namespace Google.ProtocolBuffers
}
}
public void WritePackedGroupArray<T>(int fieldNumber, string fieldName, int calculatedSize, IEnumerable<T> list)
where T : IMessageLite
{
WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited);
WriteRawVarint32((uint) calculatedSize);
foreach (IMessageLite value in list)
{
WriteGroupNoTag(value);
}
}
public void WritePackedMessageArray<T>(int fieldNumber, string fieldName, int calculatedSize,
IEnumerable<T> list)
where T : IMessageLite
// TODO(jonskeet): A lot of these are really inefficient, due to method group conversions. Fix!
public void WritePackedBoolArray(int fieldNumber, string fieldName, RepeatedField<bool> list)
{
WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited);
WriteRawVarint32((uint) calculatedSize);
foreach (IMessageLite value in list)
if (list.Count == 0)
{
WriteMessageNoTag(value);
return;
}
}
public void WritePackedStringArray(int fieldNumber, string fieldName, int calculatedSize,
IEnumerable<string> list)
{
uint size = (uint)list.Count;
WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited);
WriteRawVarint32((uint) calculatedSize);
WriteRawVarint32(size);
foreach (var value in list)
{
WriteStringNoTag(value);
WriteBoolNoTag(value);
}
}
public void WritePackedBytesArray(int fieldNumber, string fieldName, int calculatedSize,
IEnumerable<ByteString> list)
public void WritePackedInt32Array(int fieldNumber, string fieldName, RepeatedField<int> list)
{
WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited);
WriteRawVarint32((uint) calculatedSize);
foreach (var value in list)
if (list.Count == 0)
{
WriteBytesNoTag(value);
return;
}
}
public void WritePackedBoolArray(int fieldNumber, string fieldName, int calculatedSize, IEnumerable<bool> list)
{
uint size = list.CalculateSize(ComputeInt32SizeNoTag);
WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited);
WriteRawVarint32((uint) calculatedSize);
WriteRawVarint32(size);
foreach (var value in list)
{
WriteBoolNoTag(value);
WriteInt32NoTag(value);
}
}
public void WritePackedInt32Array(int fieldNumber, string fieldName, int calculatedSize, IEnumerable<int> list)
public void WritePackedSInt32Array(int fieldNumber, string fieldName, RepeatedField<int> list)
{
WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited);
WriteRawVarint32((uint) calculatedSize);
foreach (var value in list)
if (list.Count == 0)
{
WriteInt32NoTag(value);
return;
}
}
public void WritePackedSInt32Array(int fieldNumber, string fieldName, int calculatedSize, IEnumerable<int> list)
{
uint size = list.CalculateSize(ComputeSInt32SizeNoTag);
WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited);
WriteRawVarint32((uint) calculatedSize);
WriteRawVarint32(size);
foreach (var value in list)
{
WriteSInt32NoTag(value);
}
}
public void WritePackedUInt32Array(int fieldNumber, string fieldName, int calculatedSize, IEnumerable<uint> list)
public void WritePackedUInt32Array(int fieldNumber, string fieldName, RepeatedField<uint> list)
{
if (list.Count == 0)
{
return;
}
uint size = list.CalculateSize(ComputeUInt32SizeNoTag);
WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited);
WriteRawVarint32((uint) calculatedSize);
WriteRawVarint32(size);
foreach (var value in list)
{
WriteUInt32NoTag(value);
}
}
public void WritePackedFixed32Array(int fieldNumber, string fieldName, int calculatedSize,
IEnumerable<uint> list)
public void WritePackedFixed32Array(int fieldNumber, string fieldName, RepeatedField<uint> list)
{
if (list.Count == 0)
{
return;
}
uint size = (uint) list.Count * 4;
WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited);
WriteRawVarint32((uint) calculatedSize);
WriteRawVarint32(size);
foreach (var value in list)
{
WriteFixed32NoTag(value);
}
}
public void WritePackedSFixed32Array(int fieldNumber, string fieldName, int calculatedSize,
IEnumerable<int> list)
public void WritePackedSFixed32Array(int fieldNumber, string fieldName, RepeatedField<int> list)
{
if (list.Count == 0)
{
return;
}
uint size = (uint) list.Count * 4;
WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited);
WriteRawVarint32((uint) calculatedSize);
WriteRawVarint32(size);
foreach (var value in list)
{
WriteSFixed32NoTag(value);
}
}
public void WritePackedInt64Array(int fieldNumber, string fieldName, int calculatedSize, IEnumerable<long> list)
public void WritePackedInt64Array(int fieldNumber, string fieldName, RepeatedField<long> list)
{
if (list.Count == 0)
{
return;
}
uint size = list.CalculateSize(ComputeInt64SizeNoTag);
WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited);
WriteRawVarint32((uint) calculatedSize);
WriteRawVarint32(size);
foreach (var value in list)
{
WriteInt64NoTag(value);
}
}
public void WritePackedSInt64Array(int fieldNumber, string fieldName, int calculatedSize, IEnumerable<long> list)
public void WritePackedSInt64Array(int fieldNumber, string fieldName, RepeatedField<long> list)
{
if (list.Count == 0)
{
return;
}
uint size = list.CalculateSize(ComputeSInt64SizeNoTag);
WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited);
WriteRawVarint32((uint) calculatedSize);
WriteRawVarint32(size);
foreach (var value in list)
{
WriteSInt64NoTag(value);
}
}
public void WritePackedUInt64Array(int fieldNumber, string fieldName, int calculatedSize,
IEnumerable<ulong> list)
public void WritePackedUInt64Array(int fieldNumber, string fieldName, RepeatedField<ulong> list)
{
if (list.Count == 0)
{
return;
}
uint size = list.CalculateSize(ComputeUInt64SizeNoTag);
WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited);
WriteRawVarint32((uint) calculatedSize);
WriteRawVarint32(size);
foreach (var value in list)
{
WriteUInt64NoTag(value);
}
}
public void WritePackedFixed64Array(int fieldNumber, string fieldName, int calculatedSize,
IEnumerable<ulong> list)
public void WritePackedFixed64Array(int fieldNumber, string fieldName, RepeatedField<ulong> list)
{
if (list.Count == 0)
{
return;
}
uint size = (uint) list.Count * 8;
WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited);
WriteRawVarint32((uint) calculatedSize);
WriteRawVarint32(size);
foreach (var value in list)
{
WriteFixed64NoTag(value);
}
}
public void WritePackedSFixed64Array(int fieldNumber, string fieldName, int calculatedSize,
IEnumerable<long> list)
public void WritePackedSFixed64Array(int fieldNumber, string fieldName, RepeatedField<long> list)
{
if (list.Count == 0)
{
return;
}
uint size = (uint) list.Count * 8;
WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited);
WriteRawVarint32((uint) calculatedSize);
WriteRawVarint32(size);
foreach (var value in list)
{
WriteSFixed64NoTag(value);
}
}
public void WritePackedDoubleArray(int fieldNumber, string fieldName, int calculatedSize,
IEnumerable<double> list)
public void WritePackedDoubleArray(int fieldNumber, string fieldName, RepeatedField<double> list)
{
if (list.Count == 0)
{
return;
}
uint size = (uint) list.Count * 8;
WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited);
WriteRawVarint32((uint) calculatedSize);
WriteRawVarint32(size);
foreach (var value in list)
{
WriteDoubleNoTag(value);
}
}
public void WritePackedFloatArray(int fieldNumber, string fieldName, int calculatedSize, IEnumerable<float> list)
public void WritePackedFloatArray(int fieldNumber, string fieldName, RepeatedField<float> list)
{
if (list.Count == 0)
{
return;
}
uint size = (uint) list.Count * 4;
WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited);
WriteRawVarint32((uint) calculatedSize);
WriteRawVarint32(size);
foreach (var value in list)
{
WriteFloatNoTag(value);
}
}
public void WritePackedEnumArray<T>(int fieldNumber, string fieldName, int calculatedSize, IEnumerable<T> list)
public void WritePackedEnumArray<T>(int fieldNumber, string fieldName, RepeatedField<T> list)
where T : struct, IComparable, IFormattable
{
WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited);
WriteRawVarint32((uint) calculatedSize);
if (list is ICastArray)
if (list.Count == 0)
{
foreach (int value in ((ICastArray) list).CastArray<int>())
{
WriteEnumNoTag(value);
}
return;
}
else
uint size = list.CalculateSize(ComputeEnumSizeNoTag);
WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited);
WriteRawVarint32(size);
foreach (T value in list)
{
foreach (object value in list)
{
WriteEnumNoTag((int) value);
}
WriteEnumNoTag(value);
}
}

@ -33,7 +33,7 @@ using System;
using System.Collections;
using System.Collections.Generic;
namespace Google.ProtocolBuffers.Collections
namespace Google.Protobuf.Collections
{
/// <summary>
/// Utility class for dictionaries.

@ -32,7 +32,7 @@
using System;
using System.Collections;
namespace Google.ProtocolBuffers.Collections
namespace Google.Protobuf.Collections
{
/// <summary>
/// Utility class for IEnumerable (and potentially the generic version in the future).

@ -1,58 +0,0 @@
// 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.
using System.Collections.Generic;
namespace Google.ProtocolBuffers.Collections
{
/// <summary>
/// A list which has an Add method which accepts an IEnumerable[T].
/// This allows whole collections to be added easily using collection initializers.
/// It causes a potential overload confusion if T : IEnumerable[T], but in
/// practice that won't happen in protocol buffers.
/// </summary>
/// <remarks>This is only currently implemented by PopsicleList, and it's likely
/// to stay that way - hence the name. More genuinely descriptive names are
/// horribly ugly. (At least, the ones the author could think of...)</remarks>
/// <typeparam name="T">The element type of the list</typeparam>
public interface IPopsicleList<T> : IList<T>
{
void Add(IEnumerable<T> collection);
}
/// <summary>
/// Used to efficiently cast the elements of enumerations
/// </summary>
internal interface ICastArray
{
IEnumerable<TItemType> CastArray<TItemType>();
}
}

@ -32,7 +32,7 @@
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Google.ProtocolBuffers.Collections
namespace Google.Protobuf.Collections
{
/// <summary>
/// Utility non-generic class for calling into Lists{T} using type inference.

@ -1,208 +0,0 @@
// 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.
using System;
using System.Collections;
using System.Collections.Generic;
namespace Google.ProtocolBuffers.Collections
{
/// <summary>
/// Proxies calls to a <see cref="List{T}" />, but allows the list
/// to be made read-only (with the <see cref="MakeReadOnly" /> method),
/// after which any modifying methods throw <see cref="NotSupportedException" />.
/// </summary>
public sealed class PopsicleList<T> : IPopsicleList<T>, ICastArray
{
private static readonly bool CheckForNull = default(T) == null;
private static readonly T[] EmptySet = new T[0];
private List<T> items;
private bool readOnly;
/// <summary>
/// Makes this list read-only ("freezes the popsicle"). From this
/// point on, mutating methods (Clear, Add etc) will throw a
/// NotSupportedException. There is no way of "defrosting" the list afterwards.
/// </summary>
public void MakeReadOnly()
{
readOnly = true;
}
public int IndexOf(T item)
{
return items == null ? -1 : items.IndexOf(item);
}
public void Insert(int index, T item)
{
ValidateModification();
if (CheckForNull)
{
ThrowHelper.ThrowIfNull(item);
}
items.Insert(index, item);
}
public void RemoveAt(int index)
{
ValidateModification();
items.RemoveAt(index);
}
public T this[int index]
{
get
{
if (items == null)
{
throw new ArgumentOutOfRangeException();
}
return items[index];
}
set
{
ValidateModification();
if (CheckForNull)
{
ThrowHelper.ThrowIfNull(value);
}
items[index] = value;
}
}
public void Add(T item)
{
ValidateModification();
if (CheckForNull)
{
ThrowHelper.ThrowIfNull(item);
}
items.Add(item);
}
public void Clear()
{
ValidateModification();
items.Clear();
}
public bool Contains(T item)
{
return items == null ? false : items.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
if (items != null)
{
items.CopyTo(array, arrayIndex);
}
}
public int Count
{
get { return items == null ? 0 : items.Count; }
}
public bool IsReadOnly
{
get { return readOnly; }
}
public bool Remove(T item)
{
ValidateModification();
return items.Remove(item);
}
public IEnumerator<T> GetEnumerator()
{
IEnumerable<T> tenum = (IEnumerable<T>)items ?? EmptySet;
return tenum.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void Add(IEnumerable<T> collection)
{
ValidateModification();
ThrowHelper.ThrowIfNull(collection);
if (!CheckForNull || collection is PopsicleList<T>)
{
items.AddRange(collection);
}
else
{
// Assumption, it's ok to enumerate collections more than once.
if (collection is ICollection<T>)
{
ThrowHelper.ThrowIfAnyNull(collection);
items.AddRange(collection);
}
else
{
foreach (T item in collection)
{
ThrowHelper.ThrowIfNull(item);
items.Add(item);
}
}
}
}
private void ValidateModification()
{
if (readOnly)
{
throw new NotSupportedException("List is read-only");
}
if (items == null)
{
items = new List<T>();
}
}
IEnumerable<TItemType> ICastArray.CastArray<TItemType>()
{
if (items == null)
{
return PopsicleList<TItemType>.EmptySet;
}
return (TItemType[]) (object) items.ToArray();
}
}
}

@ -33,7 +33,7 @@ using System;
using System.Collections;
using System.Collections.Generic;
namespace Google.ProtocolBuffers.Collections
namespace Google.Protobuf.Collections
{
/// <summary>
/// Read-only wrapper around another dictionary.

@ -0,0 +1,168 @@
using System;
using System.Collections;
using System.Collections.Generic;
namespace Google.Protobuf.Collections
{
public sealed class RepeatedField<T> : IList<T>, IEquatable<RepeatedField<T>>
{
private readonly List<T> list = new List<T>();
public void Add(T item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
list.Add(item);
}
public void Clear()
{
list.Clear();
}
public bool Contains(T item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
return list.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
list.CopyTo(array);
}
public bool Remove(T item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
return list.Remove(item);
}
public int Count { get { return list.Count; } }
// TODO(jonskeet): If we implement freezing, make this reflect it.
public bool IsReadOnly { get { return false; } }
public void Add(RepeatedField<T> values)
{
if (values == null)
{
throw new ArgumentNullException("values");
}
// We know that all the values will be valid, because it's a RepeatedField.
list.AddRange(values);
}
public void Add(IEnumerable<T> values)
{
if (values == null)
{
throw new ArgumentNullException("values");
}
foreach (T item in values)
{
Add(item);
}
}
// TODO(jonskeet): Create our own mutable struct for this, rather than relying on List<T>.
public List<T>.Enumerator GetEnumerator()
{
return list.GetEnumerator();
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return list.GetEnumerator();
}
public override bool Equals(object obj)
{
return Equals(obj as RepeatedField<T>);
}
public override int GetHashCode()
{
int hash = 23;
foreach (T item in this)
{
hash = hash * 31 + item.GetHashCode();
}
return hash;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public bool Equals(RepeatedField<T> other)
{
if (ReferenceEquals(other, null))
{
return false;
}
if (ReferenceEquals(other, this))
{
return true;
}
if (other.Count != this.Count)
{
return false;
}
// TODO(jonskeet): Does this box for enums?
EqualityComparer<T> comparer = EqualityComparer<T>.Default;
for (int i = 0; i < Count; i++)
{
if (!comparer.Equals(this[i], other[i]))
{
return false;
}
}
return true;
}
public int IndexOf(T item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
return list.IndexOf(item);
}
public void Insert(int index, T item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
list.Insert(index, item);
}
public void RemoveAt(int index)
{
list.RemoveAt(index);
}
public T this[int index]
{
get { return list[index]; }
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
list[index] = value;
}
}
}
}

@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Google.Protobuf.Collections
{
public static class RepeatedFieldExtensions
{
internal static uint CalculateSize<T>(this RepeatedField<T> list, Func<T, int> sizeComputer)
{
int size = 0;
foreach (var item in list)
{
size += sizeComputer(item);
}
return (uint)size;
}
/*
/// <summary>
/// Calculates the serialized data size, including one tag per value.
/// </summary>
public static int CalculateTotalSize<T>(this RepeatedField<T> list, int tagSize, Func<T, int> sizeComputer)
{
if (list.Count == 0)
{
return 0;
}
return (int)(dataSize + tagSize * list.Count);
}
/// <summary>
/// Calculates the serialized data size, as a packed array (tag, length, data).
/// </summary>
public static int CalculateTotalPackedSize(int tagSize)
{
if (Count == 0)
{
return 0;
}
uint dataSize = CalculateSize();
return tagSize + CodedOutputStream.ComputeRawVarint32Size(dataSize) + (int)dataSize;
}
*/
}
}

@ -29,7 +29,7 @@
// 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.
namespace Google.ProtocolBuffers.DescriptorProtos
namespace Google.Protobuf.DescriptorProtos
{
/// <summary>
/// Interface implemented by all DescriptorProtos. The generator doesn't

@ -33,7 +33,7 @@
// This file just contains partial classes for each of the
// autogenerated classes, so that they implement
// IDescriptorProto
namespace Google.ProtocolBuffers.DescriptorProtos
namespace Google.Protobuf.DescriptorProtos
{
public partial class DescriptorProto : IDescriptorProto<MessageOptions>
{

@ -29,10 +29,11 @@
// 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.
using Google.ProtocolBuffers.DescriptorProtos;
using Google.Protobuf.DescriptorProtos;
namespace Google.ProtocolBuffers.Descriptors
namespace Google.Protobuf.Descriptors
{
// TODO(jonskeet): The descriptor type hierarchy needs changing so that we can hide the descriptor protos.
/// <summary>
/// Base class for nearly all descriptors, providing common functionality.
/// </summary>

@ -34,7 +34,7 @@ using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace Google.ProtocolBuffers.Descriptors
namespace Google.Protobuf.Descriptors
{
/// <summary>
/// Contains lookup tables containing all the descriptors defined in a particular file.
@ -85,7 +85,7 @@ namespace Google.ProtocolBuffers.Descriptors
/// <param name="fullName">Fully-qualified name to look up</param>
/// <returns>The symbol with the given name and type,
/// or null if the symbol doesn't exist or has the wrong type</returns>
internal T FindSymbol<T>(string fullName) where T : class, IDescriptor
internal T FindSymbol<T>(string fullName) where T : class
{
IDescriptor result;
descriptorsByName.TryGetValue(fullName, out result);

@ -30,9 +30,9 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System.Collections.Generic;
using Google.ProtocolBuffers.Collections;
using Google.Protobuf.Collections;
namespace Google.ProtocolBuffers.Descriptors
namespace Google.Protobuf.Descriptors
{
/// <summary>
/// Internal class containing utility methods when working with descriptors.

@ -31,7 +31,7 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
namespace Google.ProtocolBuffers.Descriptors
namespace Google.Protobuf.Descriptors
{
/// <summary>
/// Thrown when building descriptors fails because the source DescriptorProtos
@ -40,7 +40,6 @@ namespace Google.ProtocolBuffers.Descriptors
public sealed class DescriptorValidationException : Exception
{
private readonly String name;
private readonly IMessage proto;
private readonly string description;
/// <value>
@ -51,14 +50,6 @@ namespace Google.ProtocolBuffers.Descriptors
get { return name; }
}
/// <value>
/// The protocol message representation of the invalid descriptor.
/// </value>
public IMessage ProblemProto
{
get { return proto; }
}
/// <value>
/// A human-readable description of the error. (The Message property
/// is made up of the descriptor's name and this description.)
@ -75,7 +66,6 @@ namespace Google.ProtocolBuffers.Descriptors
// don't want to expose it directly to the user. So, we only provide
// the name and the original proto.
name = problemDescriptor.FullName;
proto = problemDescriptor.Proto;
this.description = description;
}
@ -83,7 +73,6 @@ namespace Google.ProtocolBuffers.Descriptors
base(problemDescriptor.FullName + ": " + description, cause)
{
name = problemDescriptor.FullName;
proto = problemDescriptor.Proto;
this.description = description;
}
}

@ -30,15 +30,14 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System.Collections.Generic;
using Google.ProtocolBuffers.DescriptorProtos;
using Google.Protobuf.DescriptorProtos;
namespace Google.ProtocolBuffers.Descriptors
namespace Google.Protobuf.Descriptors
{
/// <summary>
/// Descriptor for an enum type in a .proto file.
/// </summary>
public sealed class EnumDescriptor : IndexedDescriptorBase<EnumDescriptorProto, EnumOptions>,
IEnumLiteMap<EnumValueDescriptor>
public sealed class EnumDescriptor : IndexedDescriptorBase<EnumDescriptorProto, EnumOptions>
{
private readonly MessageDescriptor containingType;
private readonly IList<EnumValueDescriptor> values;
@ -48,14 +47,14 @@ namespace Google.ProtocolBuffers.Descriptors
{
containingType = parent;
if (proto.ValueCount == 0)
if (proto.Value.Count == 0)
{
// We cannot allow enums with no values because this would mean there
// would be no valid default value for fields of this type.
throw new DescriptorValidationException(this, "Enums must contain at least one value.");
}
values = DescriptorUtil.ConvertAndMakeReadOnly(proto.ValueList,
values = DescriptorUtil.ConvertAndMakeReadOnly(proto.Value,
(value, i) => new EnumValueDescriptor(value, file, this, i));
File.DescriptorPool.AddSymbol(this);
@ -77,14 +76,6 @@ namespace Google.ProtocolBuffers.Descriptors
get { return values; }
}
/// <summary>
/// Logic moved from FieldSet to continue current behavior
/// </summary>
public bool IsValidValue(IEnumLite value)
{
return value is EnumValueDescriptor && ((EnumValueDescriptor) value).EnumDescriptor == this;
}
/// <summary>
/// Finds an enum value by number. If multiple enum values have the
/// same number, this returns the first defined value with that number.
@ -94,16 +85,6 @@ namespace Google.ProtocolBuffers.Descriptors
return File.DescriptorPool.FindEnumValueByNumber(this, number);
}
IEnumLite IEnumLiteMap.FindValueByNumber(int number)
{
return FindValueByNumber(number);
}
IEnumLite IEnumLiteMap.FindValueByName(string name)
{
return FindValueByName(name);
}
/// <summary>
/// Finds an enum value by name.
/// </summary>
@ -119,7 +100,7 @@ namespace Google.ProtocolBuffers.Descriptors
base.ReplaceProto(newProto);
for (int i = 0; i < values.Count; i++)
{
values[i].ReplaceProto(newProto.GetValue(i));
values[i].ReplaceProto(newProto.Value[i]);
}
}
}

@ -29,15 +29,14 @@
// 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.
using Google.ProtocolBuffers.DescriptorProtos;
using Google.Protobuf.DescriptorProtos;
namespace Google.ProtocolBuffers.Descriptors
namespace Google.Protobuf.Descriptors
{
/// <summary>
/// Descriptor for a single enum value within an enum in a .proto file.
/// </summary>
public sealed class EnumValueDescriptor : IndexedDescriptorBase<EnumValueDescriptorProto, EnumValueOptions>,
IEnumLite
public sealed class EnumValueDescriptor : IndexedDescriptorBase<EnumValueDescriptorProto, EnumValueOptions>
{
private readonly EnumDescriptor enumDescriptor;

@ -32,23 +32,22 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using Google.ProtocolBuffers.Collections;
using Google.ProtocolBuffers.DescriptorProtos;
using Google.Protobuf.Collections;
using Google.Protobuf.DescriptorProtos;
namespace Google.ProtocolBuffers.Descriptors
namespace Google.Protobuf.Descriptors
{
/// <summary>
/// Descriptor for a field or extension within a message in a .proto file.
/// </summary>
public sealed class FieldDescriptor : IndexedDescriptorBase<FieldDescriptorProto, FieldOptions>,
IComparable<FieldDescriptor>, IFieldDescriptorLite
IComparable<FieldDescriptor>
{
private readonly MessageDescriptor extensionScope;
private EnumDescriptor enumType;
private MessageDescriptor messageType;
private MessageDescriptor containingType;
private OneofDescriptor containingOneof;
private object defaultValue;
private FieldType fieldType;
private MappedType mappedType;
@ -58,7 +57,7 @@ namespace Google.ProtocolBuffers.Descriptors
MessageDescriptor parent, int index, bool isExtension)
: base(proto, file, ComputeFullName(file, parent, proto.Name), index)
{
if (proto.HasType)
if (proto.Type != 0)
{
fieldType = GetFieldTypeFromProtoType(proto.Type);
mappedType = FieldTypeToMappedTypeMap[fieldType];
@ -72,7 +71,7 @@ namespace Google.ProtocolBuffers.Descriptors
if (isExtension)
{
if (!proto.HasExtendee)
if (proto.Extendee != "")
{
throw new DescriptorValidationException(this,
"FieldDescriptorProto.Extendee not set for extension field.");
@ -89,15 +88,10 @@ namespace Google.ProtocolBuffers.Descriptors
}
else
{
if (proto.HasExtendee)
{
throw new DescriptorValidationException(this,
"FieldDescriptorProto.Extendee set for non-extension field.");
}
containingType = parent;
if (proto.HasOneofIndex)
if (proto.OneofIndex != 0)
{
if (proto.OneofIndex < 0 || proto.OneofIndex >= parent.Proto.OneofDeclCount)
if (proto.OneofIndex < 0 || proto.OneofIndex >= parent.Proto.OneofDecl.Count)
{
throw new DescriptorValidationException(this,
"FieldDescriptorProto.oneof_index is out of range for type " + parent.Name);
@ -213,48 +207,15 @@ namespace Google.ProtocolBuffers.Descriptors
get { return Proto.Options.Packed; }
}
/// <valule>
/// Indicates whether or not the field had an explicitly-defined default value.
/// </value>
public bool HasDefaultValue
{
get { return Proto.HasDefaultValue; }
}
/// <value>
/// The field's default value. Valid for all types except messages
/// and groups. For all other types, the object returned is of the
/// same class that would be returned by IMessage[this].
/// For repeated fields this will always be an empty immutable list compatible with IList[object].
/// For message fields it will always be null. For singular values, it will depend on the descriptor.
/// Indicates whether or not this field is an extension. (Only relevant when parsing
/// the proto2 descriptor...)
/// </value>
public object DefaultValue
internal bool IsExtension
{
get
{
if (MappedType == MappedType.Message)
{
throw new InvalidOperationException(
"FieldDescriptor.DefaultValue called on an embedded message field.");
}
return defaultValue;
}
get { return Proto.Extendee != ""; }
}
/// <value>
/// Indicates whether or not this field is an extension.
/// </value>
public bool IsExtension
{
get { return Proto.HasExtendee; }
}
/*
* Get the field's containing type. For extensions, this is the type being
* extended, not the location where the extension was defined. See
* {@link #getExtensionScope()}.
*/
/// <summary>
/// Get the field's containing type. For extensions, this is the type being
/// extended, not the location where the extension was defined. See
@ -335,27 +296,6 @@ namespace Google.ProtocolBuffers.Descriptors
return FieldNumber - other.FieldNumber;
}
/// <summary>
/// Compares this descriptor with another one, ordering in "canonical" order
/// which simply means ascending order by field number. <paramref name="other"/>
/// must be a field of the same type, i.e. the <see cref="ContainingType"/> of
/// both fields must be the same.
/// </summary>
public int CompareTo(IFieldDescriptorLite other)
{
return FieldNumber - other.FieldNumber;
}
IEnumLiteMap IFieldDescriptorLite.EnumType
{
get { return EnumType; }
}
bool IFieldDescriptorLite.MessageSetWireFormat
{
get { return ContainingType.Options.MessageSetWireFormat; }
}
/// <summary>
/// For enum fields, returns the field's type.
/// </summary>
@ -410,29 +350,12 @@ namespace Google.ProtocolBuffers.Descriptors
/// </summary>
internal void CrossLink()
{
if (Proto.HasExtendee)
{
IDescriptor extendee = File.DescriptorPool.LookupSymbol(Proto.Extendee, this);
if (!(extendee is MessageDescriptor))
{
throw new DescriptorValidationException(this, "\"" + Proto.Extendee + "\" is not a message type.");
}
containingType = (MessageDescriptor) extendee;
if (!containingType.IsExtensionNumber(FieldNumber))
{
throw new DescriptorValidationException(this,
"\"" + containingType.FullName + "\" does not declare " +
FieldNumber + " as an extension number.");
}
}
if (Proto.HasTypeName)
if (Proto.TypeName != "")
{
IDescriptor typeDescriptor =
File.DescriptorPool.LookupSymbol(Proto.TypeName, this);
if (!Proto.HasType)
if (Proto.Type != 0)
{
// Choose field type based on symbol.
if (typeDescriptor is MessageDescriptor)
@ -460,7 +383,7 @@ namespace Google.ProtocolBuffers.Descriptors
}
messageType = (MessageDescriptor) typeDescriptor;
if (Proto.HasDefaultValue)
if (Proto.DefaultValue != "")
{
throw new DescriptorValidationException(this, "Messages can't have default values.");
}
@ -486,126 +409,14 @@ namespace Google.ProtocolBuffers.Descriptors
}
}
// We don't attempt to parse the default value until here because for
// enums we need the enum type's descriptor.
if (Proto.HasDefaultValue)
{
if (IsRepeated)
{
throw new DescriptorValidationException(this, "Repeated fields cannot have default values.");
}
try
{
switch (FieldType)
{
case FieldType.Int32:
case FieldType.SInt32:
case FieldType.SFixed32:
defaultValue = TextFormat.ParseInt32(Proto.DefaultValue);
break;
case FieldType.UInt32:
case FieldType.Fixed32:
defaultValue = TextFormat.ParseUInt32(Proto.DefaultValue);
break;
case FieldType.Int64:
case FieldType.SInt64:
case FieldType.SFixed64:
defaultValue = TextFormat.ParseInt64(Proto.DefaultValue);
break;
case FieldType.UInt64:
case FieldType.Fixed64:
defaultValue = TextFormat.ParseUInt64(Proto.DefaultValue);
break;
case FieldType.Float:
defaultValue = TextFormat.ParseFloat(Proto.DefaultValue);
break;
case FieldType.Double:
defaultValue = TextFormat.ParseDouble(Proto.DefaultValue);
break;
case FieldType.Bool:
if (Proto.DefaultValue == "true")
{
defaultValue = true;
}
else if (Proto.DefaultValue == "false")
{
defaultValue = false;
}
else
{
throw new FormatException("Boolean values must be \"true\" or \"false\"");
}
break;
case FieldType.String:
defaultValue = Proto.DefaultValue;
break;
case FieldType.Bytes:
try
{
defaultValue = TextFormat.UnescapeBytes(Proto.DefaultValue);
}
catch (FormatException e)
{
throw new DescriptorValidationException(this,
"Couldn't parse default value: " + e.Message);
}
break;
case FieldType.Enum:
defaultValue = enumType.FindValueByName(Proto.DefaultValue);
if (defaultValue == null)
{
throw new DescriptorValidationException(this,
"Unknown enum default value: \"" +
Proto.DefaultValue + "\"");
}
break;
case FieldType.Message:
case FieldType.Group:
throw new DescriptorValidationException(this, "Message type had default value.");
}
}
catch (FormatException e)
{
DescriptorValidationException validationException =
new DescriptorValidationException(this,
"Could not parse default value: \"" + Proto.DefaultValue +
"\"", e);
throw validationException;
}
}
else
{
// Determine the default default for this field.
if (IsRepeated)
{
defaultValue = Lists<object>.Empty;
}
else
{
switch (MappedType)
{
case MappedType.Enum:
// We guarantee elsewhere that an enum type always has at least
// one possible value.
defaultValue = enumType.Values[0];
break;
case MappedType.Message:
defaultValue = null;
break;
default:
defaultValue = GetDefaultValueForMappedType(MappedType);
break;
}
}
}
// Note: no attempt to perform any default value parsing
if (!IsExtension)
{
File.DescriptorPool.AddFieldByNumber(this);
}
if (containingType != null && containingType.Options.MessageSetWireFormat)
if (containingType != null && containingType.Options != null && containingType.Options.MessageSetWireFormat)
{
if (IsExtension)
{

@ -32,9 +32,9 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using Google.ProtocolBuffers.Collections;
using Google.Protobuf.Collections;
namespace Google.ProtocolBuffers.Descriptors
namespace Google.Protobuf.Descriptors
{
/// <summary>
/// Defined specifically for the <see cref="FieldType" /> enumeration,

@ -30,7 +30,7 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace Google.ProtocolBuffers.Descriptors
namespace Google.Protobuf.Descriptors
{
/// <summary>
/// Enumeration of all the possible field types. The odd formatting is to make it very clear

@ -33,10 +33,10 @@ using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using Google.ProtocolBuffers.DescriptorProtos;
using FileOptions = Google.ProtocolBuffers.DescriptorProtos.FileOptions;
using Google.Protobuf.DescriptorProtos;
using FileOptions = Google.Protobuf.DescriptorProtos.FileOptions;
namespace Google.ProtocolBuffers.Descriptors
namespace Google.Protobuf.Descriptors
{
/// <summary>
/// Describes a .proto file, including everything defined within.
@ -75,19 +75,19 @@ namespace Google.ProtocolBuffers.Descriptors
pool.AddPackage(Package, this);
messageTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.MessageTypeList,
messageTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.MessageType,
(message, index) =>
new MessageDescriptor(message, this, null, index));
enumTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.EnumTypeList,
enumTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.EnumType,
(enumType, index) =>
new EnumDescriptor(enumType, this, null, index));
services = DescriptorUtil.ConvertAndMakeReadOnly(proto.ServiceList,
services = DescriptorUtil.ConvertAndMakeReadOnly(proto.Service,
(service, index) =>
new ServiceDescriptor(service, this, index));
extensions = DescriptorUtil.ConvertAndMakeReadOnly(proto.ExtensionList,
extensions = DescriptorUtil.ConvertAndMakeReadOnly(proto.Extension,
(field, index) =>
new FieldDescriptor(field, this, null, index, true));
}
@ -104,14 +104,14 @@ namespace Google.ProtocolBuffers.Descriptors
nameToFileMap[file.Name] = file;
}
var publicDependencies = new List<FileDescriptor>();
for (int i = 0; i < proto.PublicDependencyCount; i++)
for (int i = 0; i < proto.PublicDependency.Count; i++)
{
int index = proto.PublicDependencyList[i];
if (index < 0 || index >= proto.DependencyCount)
int index = proto.PublicDependency[i];
if (index < 0 || index >= proto.Dependency.Count)
{
throw new DescriptorValidationException(@this, "Invalid public dependency index.");
}
string name = proto.DependencyList[index];
string name = proto.Dependency[index];
FileDescriptor file = nameToFileMap[name];
if (file == null)
{
@ -371,7 +371,7 @@ namespace Google.ProtocolBuffers.Descriptors
/// </summary>
public static FileDescriptor InternalBuildGeneratedFileFrom(byte[] descriptorData, FileDescriptor[] dependencies)
{
return InternalBuildGeneratedFileFrom(descriptorData, dependencies, x => null);
return InternalBuildGeneratedFileFrom(descriptorData, dependencies, x => { });
}
/// <summary>
@ -384,9 +384,7 @@ namespace Google.ProtocolBuffers.Descriptors
/// in descriptor.proto. The callback may also return null to indicate that
/// no extensions are used in the descriptor.
/// </summary>
/// <param name="descriptor"></param>
/// <returns></returns>
public delegate ExtensionRegistry InternalDescriptorAssigner(FileDescriptor descriptor);
public delegate void InternalDescriptorAssigner(FileDescriptor descriptor);
public static FileDescriptor InternalBuildGeneratedFileFrom(byte[] descriptorData,
FileDescriptor[] dependencies,
@ -395,7 +393,7 @@ namespace Google.ProtocolBuffers.Descriptors
FileDescriptorProto proto;
try
{
proto = FileDescriptorProto.ParseFrom(descriptorData);
proto = FileDescriptorProto.Parser.ParseFrom(descriptorData);
}
catch (InvalidProtocolBufferException e)
{
@ -414,22 +412,7 @@ namespace Google.ProtocolBuffers.Descriptors
throw new ArgumentException("Invalid embedded descriptor for \"" + proto.Name + "\".", e);
}
ExtensionRegistry registry = descriptorAssigner(result);
if (registry != null)
{
// We must re-parse the proto using the registry.
try
{
proto = FileDescriptorProto.ParseFrom(descriptorData, registry);
}
catch (InvalidProtocolBufferException e)
{
throw new ArgumentException("Failed to parse protocol buffer descriptor for generated code.", e);
}
result.ReplaceProto(proto);
}
descriptorAssigner(result);
return result;
}
@ -449,22 +432,22 @@ namespace Google.ProtocolBuffers.Descriptors
for (int i = 0; i < messageTypes.Count; i++)
{
messageTypes[i].ReplaceProto(proto.GetMessageType(i));
messageTypes[i].ReplaceProto(proto.MessageType[i]);
}
for (int i = 0; i < enumTypes.Count; i++)
{
enumTypes[i].ReplaceProto(proto.GetEnumType(i));
enumTypes[i].ReplaceProto(proto.EnumType[i]);
}
for (int i = 0; i < services.Count; i++)
{
services[i].ReplaceProto(proto.GetService(i));
services[i].ReplaceProto(proto.Service[i]);
}
for (int i = 0; i < extensions.Count; i++)
{
extensions[i].ReplaceProto(proto.GetExtension(i));
extensions[i].ReplaceProto(proto.Extension[i]);
}
}

@ -30,7 +30,7 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace Google.ProtocolBuffers.Descriptors
namespace Google.Protobuf.Descriptors
{
/// <summary>
/// The non-generic form of the IDescriptor interface. Useful for describing a general
@ -48,7 +48,7 @@ namespace Google.ProtocolBuffers.Descriptors
/// Strongly-typed form of the IDescriptor interface.
/// </summary>
/// <typeparam name="TProto">Protocol buffer type underlying this descriptor type</typeparam>
public interface IDescriptor<TProto> : IDescriptor where TProto : IMessage
internal interface IDescriptor<TProto> : IDescriptor where TProto : IMessage
{
new TProto Proto { get; }
}

@ -29,9 +29,9 @@
// 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.
using Google.ProtocolBuffers.DescriptorProtos;
using Google.Protobuf.DescriptorProtos;
namespace Google.ProtocolBuffers.Descriptors
namespace Google.Protobuf.Descriptors
{
/// <summary>
/// Base class for descriptors which are also indexed. This is all of them other than

@ -30,7 +30,7 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace Google.ProtocolBuffers.Descriptors
namespace Google.Protobuf.Descriptors
{
/// <summary>
/// Type as it's mapped onto a .NET type.

@ -31,9 +31,9 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using Google.ProtocolBuffers.DescriptorProtos;
using Google.Protobuf.DescriptorProtos;
namespace Google.ProtocolBuffers.Descriptors
namespace Google.Protobuf.Descriptors
{
/// <summary>
/// Describes a message type.
@ -53,33 +53,33 @@ namespace Google.ProtocolBuffers.Descriptors
{
containingType = parent;
oneofs = DescriptorUtil.ConvertAndMakeReadOnly(proto.OneofDeclList,
oneofs = DescriptorUtil.ConvertAndMakeReadOnly(proto.OneofDecl,
(oneof, index) =>
new OneofDescriptor(oneof, file, this, index));
nestedTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.NestedTypeList,
nestedTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.NestedType,
(type, index) =>
new MessageDescriptor(type, file, this, index));
enumTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.EnumTypeList,
enumTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.EnumType,
(type, index) =>
new EnumDescriptor(type, file, this, index));
// TODO(jonskeet): Sort fields first?
fields = DescriptorUtil.ConvertAndMakeReadOnly(proto.FieldList,
fields = DescriptorUtil.ConvertAndMakeReadOnly(proto.Field,
(field, index) =>
new FieldDescriptor(field, file, this, index, false));
extensions = DescriptorUtil.ConvertAndMakeReadOnly(proto.ExtensionList,
extensions = DescriptorUtil.ConvertAndMakeReadOnly(proto.Extension,
(field, index) =>
new FieldDescriptor(field, file, this, index, true));
for (int i = 0; i < proto.OneofDeclCount; i++)
for (int i = 0; i < proto.OneofDecl.Count; i++)
{
oneofs[i].fields = new FieldDescriptor[oneofs[i].FieldCount];
oneofs[i].fieldCount = 0;
}
for (int i = 0; i< proto.FieldCount; i++)
for (int i = 0; i< proto.Field.Count; i++)
{
OneofDescriptor oneofDescriptor = fields[i].ContainingOneof;
if (oneofDescriptor != null)
@ -151,7 +151,7 @@ namespace Google.ProtocolBuffers.Descriptors
/// </summary>
public bool IsExtensionNumber(int number)
{
foreach (DescriptorProto.Types.ExtensionRange range in Proto.ExtensionRangeList)
foreach (DescriptorProto.Types.ExtensionRange range in Proto.ExtensionRange)
{
if (range.Start <= number && number < range.End)
{
@ -244,7 +244,7 @@ namespace Google.ProtocolBuffers.Descriptors
// If the type allows extensions, an extension with message type could contain
// required fields, so we have to be conservative and assume such an
// extension exists.
if (Proto.ExtensionRangeCount != 0)
if (Proto.ExtensionRange.Count != 0)
{
return true;
}
@ -275,22 +275,22 @@ namespace Google.ProtocolBuffers.Descriptors
for (int i = 0; i < nestedTypes.Count; i++)
{
nestedTypes[i].ReplaceProto(newProto.GetNestedType(i));
nestedTypes[i].ReplaceProto(newProto.NestedType[i]);
}
for (int i = 0; i < enumTypes.Count; i++)
{
enumTypes[i].ReplaceProto(newProto.GetEnumType(i));
enumTypes[i].ReplaceProto(newProto.EnumType[i]);
}
for (int i = 0; i < fields.Count; i++)
{
fields[i].ReplaceProto(newProto.GetField(i));
fields[i].ReplaceProto(newProto.Field[i]);
}
for (int i = 0; i < extensions.Count; i++)
{
extensions[i].ReplaceProto(newProto.GetExtension(i));
extensions[i].ReplaceProto(newProto.Extension[i]);
}
}
}

@ -29,9 +29,9 @@
// 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.
using Google.ProtocolBuffers.DescriptorProtos;
using Google.Protobuf.DescriptorProtos;
namespace Google.ProtocolBuffers.Descriptors
namespace Google.Protobuf.Descriptors
{
/// <summary>
/// Describes a single method in a service.

@ -31,9 +31,9 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Google.ProtocolBuffers.DescriptorProtos;
using Google.Protobuf.DescriptorProtos;
namespace Google.ProtocolBuffers.Descriptors
namespace Google.Protobuf.Descriptors
{
public sealed class OneofDescriptor
{

@ -30,7 +30,7 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace Google.ProtocolBuffers.Descriptors
namespace Google.Protobuf.Descriptors
{
/// <summary>
/// Represents a package in the symbol table. We use PackageDescriptors

@ -31,9 +31,9 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using Google.ProtocolBuffers.DescriptorProtos;
using Google.Protobuf.DescriptorProtos;
namespace Google.ProtocolBuffers.Descriptors
namespace Google.Protobuf.Descriptors
{
/// <summary>
/// Describes a service type.
@ -45,7 +45,7 @@ namespace Google.ProtocolBuffers.Descriptors
public ServiceDescriptor(ServiceDescriptorProto proto, FileDescriptor file, int index)
: base(proto, file, ComputeFullName(file, null, proto.Name), index)
{
methods = DescriptorUtil.ConvertAndMakeReadOnly(proto.MethodList,
methods = DescriptorUtil.ConvertAndMakeReadOnly(proto.Method,
(method, i) => new MethodDescriptor(method, file, this, i));
file.DescriptorPool.AddSymbol(this);
@ -82,7 +82,7 @@ namespace Google.ProtocolBuffers.Descriptors
base.ReplaceProto(newProto);
for (int i = 0; i < methods.Count; i++)
{
methods[i].ReplaceProto(newProto.GetMethod(i));
methods[i].ReplaceProto(newProto.Method[i]);
}
}
}

@ -1,624 +0,0 @@
#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.Collections.Generic;
using System.IO;
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers
{
/// <summary>
/// An implementation of IMessage that can represent arbitrary types, given a MessageaDescriptor.
/// </summary>
public sealed partial class DynamicMessage : AbstractMessage<DynamicMessage, DynamicMessage.Builder>
{
private readonly MessageDescriptor type;
private readonly FieldSet fields;
private readonly FieldDescriptor[] oneofCase;
private readonly UnknownFieldSet unknownFields;
private int memoizedSize = -1;
/// <summary>
/// Creates a DynamicMessage with the given FieldSet.
/// </summary>
/// <param name="type"></param>
/// <param name="fields"></param>
/// <param name="unknownFields"></param>
private DynamicMessage(MessageDescriptor type, FieldSet fields,
FieldDescriptor[] oneofCase, UnknownFieldSet unknownFields)
{
this.type = type;
this.fields = fields;
this.oneofCase = oneofCase;
this.unknownFields = unknownFields;
}
/// <summary>
/// Returns a DynamicMessage representing the default instance of the given type.
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static DynamicMessage GetDefaultInstance(MessageDescriptor type)
{
int oneofDescriptorCount = type.Proto.OneofDeclCount;
FieldDescriptor[] oneofCase = new FieldDescriptor[oneofDescriptorCount];
return new DynamicMessage(type, FieldSet.DefaultInstance, oneofCase, UnknownFieldSet.DefaultInstance);
}
/// <summary>
/// Parses a message of the given type from the given stream.
/// </summary>
public static DynamicMessage ParseFrom(MessageDescriptor type, ICodedInputStream input)
{
Builder builder = CreateBuilder(type);
Builder dynamicBuilder = builder.MergeFrom(input);
return dynamicBuilder.BuildParsed();
}
/// <summary>
/// Parse a message of the given type from the given stream and extension registry.
/// </summary>
/// <param name="type"></param>
/// <param name="input"></param>
/// <param name="extensionRegistry"></param>
/// <returns></returns>
public static DynamicMessage ParseFrom(MessageDescriptor type, ICodedInputStream input,
ExtensionRegistry extensionRegistry)
{
Builder builder = CreateBuilder(type);
Builder dynamicBuilder = builder.MergeFrom(input, extensionRegistry);
return dynamicBuilder.BuildParsed();
}
/// <summary>
/// Parses a message of the given type from the given stream.
/// </summary>
public static DynamicMessage ParseFrom(MessageDescriptor type, Stream input)
{
Builder builder = CreateBuilder(type);
Builder dynamicBuilder = builder.MergeFrom(input);
return dynamicBuilder.BuildParsed();
}
/// <summary>
/// Parse a message of the given type from the given stream and extension registry.
/// </summary>
/// <param name="type"></param>
/// <param name="input"></param>
/// <param name="extensionRegistry"></param>
/// <returns></returns>
public static DynamicMessage ParseFrom(MessageDescriptor type, Stream input, ExtensionRegistry extensionRegistry)
{
Builder builder = CreateBuilder(type);
Builder dynamicBuilder = builder.MergeFrom(input, extensionRegistry);
return dynamicBuilder.BuildParsed();
}
/// <summary>
/// Parse <paramref name="data"/> as a message of the given type and return it.
/// </summary>
public static DynamicMessage ParseFrom(MessageDescriptor type, ByteString data)
{
Builder builder = CreateBuilder(type);
Builder dynamicBuilder = builder.MergeFrom(data);
return dynamicBuilder.BuildParsed();
}
/// <summary>
/// Parse <paramref name="data"/> as a message of the given type and return it.
/// </summary>
public static DynamicMessage ParseFrom(MessageDescriptor type, ByteString data,
ExtensionRegistry extensionRegistry)
{
Builder builder = CreateBuilder(type);
Builder dynamicBuilder = builder.MergeFrom(data, extensionRegistry);
return dynamicBuilder.BuildParsed();
}
/// <summary>
/// Parse <paramref name="data"/> as a message of the given type and return it.
/// </summary>
public static DynamicMessage ParseFrom(MessageDescriptor type, byte[] data)
{
Builder builder = CreateBuilder(type);
Builder dynamicBuilder = builder.MergeFrom(data);
return dynamicBuilder.BuildParsed();
}
/// <summary>
/// Parse <paramref name="data"/> as a message of the given type and return it.
/// </summary>
public static DynamicMessage ParseFrom(MessageDescriptor type, byte[] data, ExtensionRegistry extensionRegistry)
{
Builder builder = CreateBuilder(type);
Builder dynamicBuilder = builder.MergeFrom(data, extensionRegistry);
return dynamicBuilder.BuildParsed();
}
/// <summary>
/// Constructs a builder for the given type.
/// </summary>
public static Builder CreateBuilder(MessageDescriptor type)
{
return new Builder(type);
}
/// <summary>
/// Constructs a builder for a message of the same type as <paramref name="prototype"/>,
/// and initializes it with the same contents.
/// </summary>
/// <param name="prototype"></param>
/// <returns></returns>
public static Builder CreateBuilder(IMessage prototype)
{
return new Builder(prototype.DescriptorForType).MergeFrom(prototype);
}
// -----------------------------------------------------------------
// Implementation of IMessage interface.
public override MessageDescriptor DescriptorForType
{
get { return type; }
}
public override DynamicMessage DefaultInstanceForType
{
get { return GetDefaultInstance(type); }
}
public override IDictionary<FieldDescriptor, object> AllFields
{
get { return fields.AllFieldDescriptors; }
}
public override bool HasOneof(OneofDescriptor oneof)
{
VerifyContainingOneofType(oneof);
FieldDescriptor field = oneofCase[oneof.Index];
if (field == null)
{
return false;
}
return true;
}
public override FieldDescriptor OneofFieldDescriptor(OneofDescriptor oneof)
{
VerifyContainingOneofType(oneof);
return oneofCase[oneof.Index];
}
public override bool HasField(FieldDescriptor field)
{
VerifyContainingType(field);
return fields.HasField(field);
}
public override object this[FieldDescriptor field]
{
get
{
VerifyContainingType(field);
object result = fields[field];
if (result == null)
{
result = GetDefaultInstance(field.MessageType);
}
return result;
}
}
public override int GetRepeatedFieldCount(FieldDescriptor field)
{
VerifyContainingType(field);
return fields.GetRepeatedFieldCount(field);
}
public override object this[FieldDescriptor field, int index]
{
get
{
VerifyContainingType(field);
return fields[field, index];
}
}
public override UnknownFieldSet UnknownFields
{
get { return unknownFields; }
}
public bool Initialized
{
get { return fields.IsInitializedWithRespectTo(type.Fields); }
}
public override void WriteTo(ICodedOutputStream output)
{
fields.WriteTo(output);
if (type.Options.MessageSetWireFormat)
{
unknownFields.WriteAsMessageSetTo(output);
}
else
{
unknownFields.WriteTo(output);
}
}
public override int SerializedSize
{
get
{
int size = memoizedSize;
if (size != -1)
{
return size;
}
size = fields.SerializedSize;
if (type.Options.MessageSetWireFormat)
{
size += unknownFields.SerializedSizeAsMessageSet;
}
else
{
size += unknownFields.SerializedSize;
}
memoizedSize = size;
return size;
}
}
public override Builder CreateBuilderForType()
{
return new Builder(type);
}
public override Builder ToBuilder()
{
return CreateBuilderForType().MergeFrom(this);
}
/// <summary>
/// Verifies that the field is a field of this message.
/// </summary>
private void VerifyContainingType(FieldDescriptor field)
{
if (field.ContainingType != type)
{
throw new ArgumentException("FieldDescriptor does not match message type.");
}
}
/// <summary>
/// Verifies that the oneof is an oneof of this message.
/// </summary>
private void VerifyContainingOneofType(OneofDescriptor oneof)
{
if (oneof.ContainingType != type)
{
throw new ArgumentException("OneofDescritpor does not match message type");
}
}
/// <summary>
/// Builder for dynamic messages. Instances are created with DynamicMessage.CreateBuilder.
/// </summary>
public sealed partial class Builder : AbstractBuilder<DynamicMessage, Builder>
{
private readonly MessageDescriptor type;
private FieldSet fields;
private FieldDescriptor[] oneofCase;
private UnknownFieldSet unknownFields;
internal Builder(MessageDescriptor type)
{
this.type = type;
this.fields = FieldSet.CreateInstance();
this.unknownFields = UnknownFieldSet.DefaultInstance;
this.oneofCase = new FieldDescriptor[type.Proto.OneofDeclCount];
}
protected override Builder ThisBuilder
{
get { return this; }
}
public override Builder Clear()
{
fields.Clear();
return this;
}
public override Builder MergeFrom(IMessage other)
{
if (other.DescriptorForType != type)
{
throw new ArgumentException("MergeFrom(IMessage) can only merge messages of the same type.");
}
fields.MergeFrom(other);
MergeUnknownFields(other.UnknownFields);
for (int i = 0; i < oneofCase.Length; i++)
{
if (other.HasOneof(type.Oneofs[i]))
{
if (oneofCase[i] == null)
{
oneofCase[i] = other.OneofFieldDescriptor(type.Oneofs[i]);
} else
{
if (oneofCase[i] != other.OneofFieldDescriptor(type.Oneofs[i]))
{
fields.ClearField(oneofCase[i]);
oneofCase[i] = other.OneofFieldDescriptor(type.Oneofs[i]);
}
}
}
}
return this;
}
public override Builder MergeFrom(DynamicMessage other)
{
IMessage downcast = other;
return MergeFrom(downcast);
}
public override DynamicMessage Build()
{
if (fields != null && !IsInitialized)
{
throw new UninitializedMessageException(new DynamicMessage(type, fields, oneofCase, unknownFields));
}
return BuildPartial();
}
/// <summary>
/// Helper for DynamicMessage.ParseFrom() methods to call. Throws
/// InvalidProtocolBufferException
/// </summary>
/// <returns></returns>
internal DynamicMessage BuildParsed()
{
if (!IsInitialized)
{
throw new UninitializedMessageException(new DynamicMessage(type, fields, oneofCase, unknownFields)).
AsInvalidProtocolBufferException();
}
return BuildPartial();
}
public override DynamicMessage BuildPartial()
{
if (fields == null)
{
throw new InvalidOperationException("Build() has already been called on this Builder.");
}
fields.MakeImmutable();
DynamicMessage result = new DynamicMessage(type, fields, oneofCase, unknownFields);
fields = null;
unknownFields = null;
return result;
}
public override Builder Clone()
{
Builder result = new Builder(type);
result.fields.MergeFrom(fields);
result.oneofCase = oneofCase;
return result;
}
public override bool IsInitialized
{
get { return fields.IsInitializedWithRespectTo(type.Fields); }
}
public override Builder MergeFrom(ICodedInputStream input, ExtensionRegistry extensionRegistry)
{
UnknownFieldSet.Builder unknownFieldsBuilder = UnknownFieldSet.CreateBuilder(unknownFields);
unknownFieldsBuilder.MergeFrom(input, extensionRegistry, this);
unknownFields = unknownFieldsBuilder.Build();
return this;
}
public override MessageDescriptor DescriptorForType
{
get { return type; }
}
public override DynamicMessage DefaultInstanceForType
{
get { return GetDefaultInstance(type); }
}
public override IDictionary<FieldDescriptor, object> AllFields
{
get { return fields.AllFieldDescriptors; }
}
public override IBuilder CreateBuilderForField(FieldDescriptor field)
{
VerifyContainingType(field);
if (field.MappedType != MappedType.Message)
{
throw new ArgumentException("CreateBuilderForField is only valid for fields with message type.");
}
return new Builder(field.MessageType);
}
public override bool HasOneof(OneofDescriptor oneof)
{
VerifyContainingOneofType(oneof);
FieldDescriptor field = oneofCase[oneof.Index];
if (field == null)
{
return false;
}
return true;
}
public override FieldDescriptor OneofFieldDescriptor(OneofDescriptor oneof)
{
VerifyContainingOneofType(oneof);
return oneofCase[oneof.Index];
}
public override bool HasField(FieldDescriptor field)
{
VerifyContainingType(field);
return fields.HasField(field);
}
public override object this[FieldDescriptor field, int index]
{
get
{
VerifyContainingType(field);
return fields[field, index];
}
set
{
VerifyContainingType(field);
fields[field, index] = value;
}
}
public override object this[FieldDescriptor field]
{
get
{
VerifyContainingType(field);
object result = fields[field];
if (result == null)
{
result = GetDefaultInstance(field.MessageType);
}
return result;
}
set
{
VerifyContainingType(field);
OneofDescriptor oneof = field.ContainingOneof;
if (oneof != null)
{
int index = oneof.Index;
FieldDescriptor oldField = oneofCase[index];
if ((oldField != null) && (oldField != field))
{
fields.ClearField(oldField);
}
oneofCase[index] = field;
}
fields[field] = value;
}
}
public override Builder ClearField(FieldDescriptor field)
{
VerifyContainingType(field);
OneofDescriptor oneof = field.ContainingOneof;
if (oneof != null)
{
int index = oneof.Index;
if (oneofCase[index] == field)
{
oneofCase[index] = null;
}
}
fields.ClearField(field);
return this;
}
public override Builder ClearOneof(OneofDescriptor oneof)
{
VerifyContainingOneofType(oneof);
FieldDescriptor field = oneofCase[oneof.Index];
if (field != null)
{
ClearField(field);
}
return this;
}
public override int GetRepeatedFieldCount(FieldDescriptor field)
{
VerifyContainingType(field);
return fields.GetRepeatedFieldCount(field);
}
public override Builder AddRepeatedField(FieldDescriptor field, object value)
{
VerifyContainingType(field);
fields.AddRepeatedField(field, value);
return this;
}
public override UnknownFieldSet UnknownFields
{
get { return unknownFields; }
set { unknownFields = value; }
}
/// <summary>
/// Verifies that the field is a field of this message.
/// </summary>
/// <param name="field"></param>
private void VerifyContainingType(FieldDescriptor field)
{
if (field.ContainingType != type)
{
throw new ArgumentException("FieldDescriptor does not match message type.");
}
}
/// <summary>
/// Verifies that the oneof is an oneof of this message.
/// </summary>
private void VerifyContainingOneofType(OneofDescriptor oneof)
{
if (oneof.ContainingType != type)
{
throw new ArgumentException("OneofDescriptor does not match message type");
}
}
}
}
}

@ -0,0 +1,85 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Google.Protobuf
{
public class EnumHelper<T> where T : struct, IComparable, IFormattable
{
// TODO(jonskeet): For snmall enums, use something lighter-weight than a dictionary?
private static readonly Dictionary<int, T> _byNumber;
private static readonly Dictionary<string, T> _byName;
private const long UnknownValueBase = 0x100000000L;
static EnumHelper()
{
if (!typeof(T).IsEnum)
{
throw new InvalidOperationException(string.Format("{0} is not an enum type", typeof(T).FullName));
}
if (Enum.GetUnderlyingType(typeof(T)) != typeof(long))
{
throw new InvalidOperationException(string.Format("{0} does not have long as an underlying type", typeof(T).FullName));
}
// It will actually be a T[], but the CLR will let us convert.
long[] array = (long[])Enum.GetValues(typeof(T));
_byNumber = new Dictionary<int, T>(array.Length);
foreach (long i in array)
{
_byNumber[(int) i] = (T)(object)i;
}
string[] names = (string[])Enum.GetNames(typeof(T));
_byName = new Dictionary<string, T>();
foreach (var name in names)
{
_byName[name] = (T) Enum.Parse(typeof(T), name, false);
}
}
/// <summary>
/// Converts the given 32-bit integer into a value of the enum type.
/// If the integer is a known, named value, that is returned; otherwise,
/// a value which is outside the range of 32-bit integers but which preserves
/// the original integer is returned.
/// </summary>
public static T FromInt32(int value)
{
T validValue;
return _byNumber.TryGetValue(value, out validValue) ? validValue : FromRawValue((long) value | UnknownValueBase);
}
/// <summary>
/// Converts a value of the enum type to a 32-bit integer. This reverses
/// <see cref="Int32"/>.
/// </summary>
public static int ToInt32(T value)
{
return (int)GetRawValue(value);
}
public static bool IsKnownValue(T value)
{
long raw = GetRawValue(value);
if (raw >= int.MinValue && raw <= int.MaxValue)
{
return _byNumber.ContainsKey((int)raw);
}
return false;
}
private static long GetRawValue(T value)
{
// TODO(jonskeet): Try using expression trees to get rid of the boxing here.
return (long)(object)value;
}
private static T FromRawValue(long value)
{
// TODO(jonskeet): Try using expression trees to get rid of the boxing here.
return (T)(object)value;
}
}
}

@ -1,234 +0,0 @@
#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.Collections.Generic;
namespace Google.ProtocolBuffers
{
///<summary>
///Interface for an enum value or value descriptor, to be used in FieldSet.
///The lite library stores enum values directly in FieldSets but the full
///library stores EnumValueDescriptors in order to better support reflection.
///</summary>
public interface IEnumLite
{
int Number { get; }
string Name { get; }
}
///<summary>
///Interface for an object which maps integers to {@link EnumLite}s.
///{@link Descriptors.EnumDescriptor} implements this interface by mapping
///numbers to {@link Descriptors.EnumValueDescriptor}s. Additionally,
///every generated enum type has a static method internalGetValueMap() which
///returns an implementation of this type that maps numbers to enum values.
///</summary>
public interface IEnumLiteMap<T> : IEnumLiteMap
where T : IEnumLite
{
new T FindValueByNumber(int number);
}
public interface IEnumLiteMap
{
bool IsValidValue(IEnumLite value);
IEnumLite FindValueByNumber(int number);
IEnumLite FindValueByName(string name);
}
public class EnumLiteMap<TEnum> : IEnumLiteMap<IEnumLite>
where TEnum : struct, IComparable, IFormattable
{
private struct EnumValue : IEnumLite
{
private readonly TEnum value;
public EnumValue(TEnum value)
{
this.value = value;
}
int IEnumLite.Number
{
get { return Convert.ToInt32(value); }
}
string IEnumLite.Name
{
get { return value.ToString(); }
}
}
public IEnumLite FindValueByNumber(int number)
{
TEnum val = default(TEnum);
if (EnumParser<TEnum>.TryConvert(number, ref val))
{
return new EnumValue(val);
}
return null;
}
public IEnumLite FindValueByName(string name)
{
TEnum val = default(TEnum);
if (EnumParser<TEnum>.TryConvert(name, ref val))
{
return new EnumValue(val);
}
return null;
}
public bool IsValidValue(IEnumLite value)
{
TEnum val = default(TEnum);
return EnumParser<TEnum>.TryConvert(value.Number, ref val);
}
}
public static class EnumParser<T> where T : struct, IComparable, IFormattable
{
private static readonly Dictionary<int, T> _byNumber;
private static Dictionary<string, T> _byName;
static EnumParser()
{
int[] array;
try
{
#if CLIENTPROFILE
// It will actually be a T[], but the CLR will let us convert.
array = (int[])Enum.GetValues(typeof(T));
#else
var temp = new List<T>();
foreach (var fld in typeof (T).GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static))
{
if (fld.IsLiteral && fld.FieldType == typeof(T))
{
temp.Add((T)fld.GetValue(null));
}
}
array = (int[])(object)temp.ToArray();
#endif
}
catch
{
_byNumber = null;
return;
}
_byNumber = new Dictionary<int, T>(array.Length);
foreach (int i in array)
{
_byNumber[i] = (T)(object)i;
}
}
public static bool TryConvert(object input, ref T value)
{
if (input is int || input is T)
{
return TryConvert((int)input, ref value);
}
if (input is string)
{
return TryConvert((string)input, ref value);
}
return false;
}
/// <summary>
/// Tries to convert an integer to its enum representation. This would take an out parameter,
/// but the caller uses ref, so this approach is simpler.
/// </summary>
public static bool TryConvert(int number, ref T value)
{
// null indicates an exception at construction, use native IsDefined.
if (_byNumber == null)
{
return Enum.IsDefined(typeof(T), number);
}
T converted;
if (_byNumber != null && _byNumber.TryGetValue(number, out converted))
{
value = converted;
return true;
}
return false;
}
/// <summary>
/// Tries to convert a string to its enum representation. This would take an out parameter,
/// but the caller uses ref, so this approach is simpler.
/// </summary>
public static bool TryConvert(string name, ref T value)
{
// null indicates an exception at construction, use native IsDefined/Parse.
if (_byNumber == null)
{
if (Enum.IsDefined(typeof(T), name))
{
value = (T)Enum.Parse(typeof(T), name, false);
return true;
}
return false;
}
// known race, possible multiple threads each build their own copy; however, last writer will win
var map = _byName;
if (map == null)
{
map = new Dictionary<string, T>(StringComparer.Ordinal);
foreach (var possible in _byNumber.Values)
{
map[possible.ToString()] = possible;
}
_byName = map;
}
T converted;
if (map.TryGetValue(name, out converted))
{
value = converted;
return true;
}
return false;
}
}
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save