First commit of lite code - more to come

pull/288/head
Jon Skeet 14 years ago
commit 1738462b7f
  1. 4
      .gitignore
  2. BIN
      lib/protoc.exe
  3. 72
      protos/extest/unittest_extras_full.proto
  4. 61
      protos/extest/unittest_extras_lite.proto
  5. 36
      protos/google/protobuf/descriptor.proto
  6. 122
      protos/google/protobuf/unittest.proto
  7. 8
      protos/google/protobuf/unittest_custom_options.proto
  8. 43
      protos/google/protobuf/unittest_empty.proto
  9. 1052
      protos/google/protobuf/unittest_enormous_descriptor.proto
  10. 55
      protos/google/protobuf/unittest_import_lite.proto
  11. 318
      protos/google/protobuf/unittest_lite.proto
  12. 49
      protos/google/protobuf/unittest_lite_imports_nonlite.proto
  13. 60
      protos/google/protobuf/unittest_no_generic_services.proto
  14. 2
      src/AddressBook/AddressBookProtos.cs
  15. 2
      src/ProtoGen.Test/ProtoGen.Test.csproj
  16. 24
      src/ProtoGen/EnumFieldGenerator.cs
  17. 57
      src/ProtoGen/ExtensionGenerator.cs
  18. 34
      src/ProtoGen/FieldGeneratorBase.cs
  19. 6
      src/ProtoGen/Helpers.cs
  20. 4
      src/ProtoGen/IFieldSourceGenerator.cs
  21. 13
      src/ProtoGen/MessageFieldGenerator.cs
  22. 196
      src/ProtoGen/MessageGenerator.cs
  23. 12
      src/ProtoGen/PrimitiveFieldGenerator.cs
  24. 27
      src/ProtoGen/RepeatedEnumFieldGenerator.cs
  25. 17
      src/ProtoGen/RepeatedMessageFieldGenerator.cs
  26. 17
      src/ProtoGen/RepeatedPrimitiveFieldGenerator.cs
  27. 12
      src/ProtoGen/SourceGeneratorBase.cs
  28. 36
      src/ProtoGen/UmbrellaClassGenerator.cs
  29. 192
      src/ProtocolBuffers.Test/ExtendableMessageTest.cs
  30. 50
      src/ProtocolBuffers.Test/ProtocolBuffers.Test.csproj
  31. 2
      src/ProtocolBuffers.Test/ReflectionTester.cs
  32. 2
      src/ProtocolBuffers.Test/TestProtos/UnitTestCSharpOptionsProtoFile.cs
  33. 328
      src/ProtocolBuffers.Test/TestProtos/UnitTestCustomOptionsProtoFile.cs
  34. 2
      src/ProtocolBuffers.Test/TestProtos/UnitTestEmbedOptimizeForProtoFile.cs
  35. 44
      src/ProtocolBuffers.Test/TestProtos/UnitTestEmptyProtoFile.cs
  36. 196
      src/ProtocolBuffers.Test/TestProtos/UnitTestImportLiteProtoFile.cs
  37. 2
      src/ProtocolBuffers.Test/TestProtos/UnitTestImportProtoFile.cs
  38. 2
      src/ProtocolBuffers.Test/TestProtos/UnitTestMessageSetProtoFile.cs
  39. 382
      src/ProtocolBuffers.Test/TestProtos/UnitTestNoGenericServicesProtoFile.cs
  40. 2
      src/ProtocolBuffers.Test/TestProtos/UnitTestOptimizeForProtoFile.cs
  41. 6320
      src/ProtocolBuffers.Test/TestProtos/UnitTestProtoFile.cs
  42. 67
      src/ProtocolBuffers.sln
  43. 234
      src/ProtocolBuffers/AbstractBuilder.cs
  44. 232
      src/ProtocolBuffers/AbstractBuilderLite.cs
  45. 104
      src/ProtocolBuffers/AbstractMessage.cs
  46. 133
      src/ProtocolBuffers/AbstractMessageLite.cs
  47. 7
      src/ProtocolBuffers/ByteString.cs
  48. 11
      src/ProtocolBuffers/CodedInputStream.cs
  49. 53
      src/ProtocolBuffers/CodedOutputStream.cs
  50. 2
      src/ProtocolBuffers/DescriptorProtos/CSharpOptions.cs
  51. 238
      src/ProtocolBuffers/DescriptorProtos/DescriptorProtoFile.cs
  52. 14
      src/ProtocolBuffers/Descriptors/EnumDescriptor.cs
  53. 2
      src/ProtocolBuffers/Descriptors/EnumValueDescriptor.cs
  54. 21
      src/ProtocolBuffers/Descriptors/FieldDescriptor.cs
  55. 26
      src/ProtocolBuffers/Descriptors/FieldMappingAttribute.cs
  56. 11
      src/ProtocolBuffers/DynamicMessage.cs
  57. 106
      src/ProtocolBuffers/EnumLite.cs
  58. 8
      src/ProtocolBuffers/ExtendableBuilder.cs
  59. 262
      src/ProtocolBuffers/ExtendableBuilderLite.cs
  60. 8
      src/ProtocolBuffers/ExtendableMessage.cs
  61. 184
      src/ProtocolBuffers/ExtendableMessageLite.cs
  62. 26
      src/ProtocolBuffers/ExtensionInfo.cs
  63. 62
      src/ProtocolBuffers/ExtensionRegistry.cs
  64. 179
      src/ProtocolBuffers/ExtensionRegistryLite.cs
  65. 2
      src/ProtocolBuffers/FieldAccess/RepeatedMessageAccessor.cs
  66. 2
      src/ProtocolBuffers/FieldAccess/SingleMessageAccessor.cs
  67. 199
      src/ProtocolBuffers/FieldSet.cs
  68. 8
      src/ProtocolBuffers/GeneratedBuilder.cs
  69. 117
      src/ProtocolBuffers/GeneratedBuilderLite.cs
  70. 14
      src/ProtocolBuffers/GeneratedExtensionBase.cs
  71. 294
      src/ProtocolBuffers/GeneratedExtensionLite.cs
  72. 4
      src/ProtocolBuffers/GeneratedMessage.cs
  73. 132
      src/ProtocolBuffers/GeneratedMessageLite.cs
  74. 75
      src/ProtocolBuffers/IBuilder.cs
  75. 210
      src/ProtocolBuffers/IBuilderLite.cs
  76. 38
      src/ProtocolBuffers/IMessage.cs
  77. 179
      src/ProtocolBuffers/IMessageLite.cs
  78. 6
      src/ProtocolBuffers/Properties/AssemblyInfo.cs
  79. 23
      src/ProtocolBuffers/ProtocolBuffers.csproj
  80. 115
      src/ProtocolBuffers/ProtocolBuffersLite.csproj
  81. 12
      src/ProtocolBuffers/SortedList.cs
  82. 14
      src/ProtocolBuffers/TextFormat.cs
  83. 36
      src/ProtocolBuffers/UninitializedMessageException.cs
  84. 4
      src/ProtocolBuffers/UnknownField.cs
  85. 109
      src/ProtocolBuffers/UnknownFieldSet.cs
  86. 4
      src/ProtocolBuffers/WireFormat.cs
  87. 268
      src/ProtocolBuffersLite.Test/AbstractBuilderLiteTest.cs
  88. 126
      src/ProtocolBuffersLite.Test/AbstractMessageLiteTest.cs
  89. 267
      src/ProtocolBuffersLite.Test/ExtendableBuilderLiteTest.cs
  90. 304
      src/ProtocolBuffersLite.Test/ExtendableMessageLiteTest.cs
  91. 162
      src/ProtocolBuffersLite.Test/InteropLiteTest.cs
  92. 112
      src/ProtocolBuffersLite.Test/LiteTest.cs
  93. 219
      src/ProtocolBuffersLite.Test/MissingFieldAndExtensionTest.cs
  94. 110
      src/ProtocolBuffersLite.Test/ProtocolBuffersLite.Test.csproj
  95. 115
      src/ProtocolBuffersLite.Test/ProtocolBuffersLiteMixed.Test.csproj
  96. 116
      src/ProtocolBuffersLite.Test/TestLiteByApi.cs
  97. 1803
      src/ProtocolBuffersLite.Test/TestProtos/UnitTestExtrasFullProtoFile.cs
  98. 1721
      src/ProtocolBuffersLite.Test/TestProtos/UnitTestExtrasLiteProtoFile.cs
  99. 246
      src/ProtocolBuffersLite.Test/TestProtos/UnitTestImportLiteProtoFile.cs
  100. 280
      src/ProtocolBuffersLite.Test/TestProtos/UnitTestImportProtoFile.cs
  101. Some files were not shown because too many files have changed in this diff Show More

4
.gitignore vendored

@ -8,6 +8,8 @@ src/ProtocolBuffers/obj/
src/ProtocolBuffers/objCF
src/ProtocolBuffers.Test/bin/
src/ProtocolBuffers.Test/obj/
src/ProtocolBuffersLite.Test/bin/
src/ProtocolBuffersLite.Test/obj/
src/ProtoBench/bin/
src/ProtoBench/obj/
src/ProtoDump/bin/
@ -34,4 +36,4 @@ _ReSharper.*
mono/TestResult.xml
mono/.libs
mono/*.exe
mono/*.dll
mono/*.dll

Binary file not shown.

@ -0,0 +1,72 @@
// Additional options required for C# generation. File from copyright
// line onwards is as per original distribution.
import "google/protobuf/csharp_options.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.TestProtos";
option (google.protobuf.csharp_file_options).umbrella_classname = "UnitTestExtrasFullProtoFile";
package protobuf_unittest_extra;
option optimize_for = CODE_SIZE;
option java_package = "com.google.protobuf";
message TestInteropPerson {
required string name = 1;
required int32 id = 2;
optional string email = 3;
repeated int32 codes = 10 [packed=true];
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
message PhoneNumber {
required string number = 1;
optional PhoneType type = 2 [default = HOME];
}
repeated PhoneNumber phone = 4;
repeated group Addresses = 5 {
required string address = 1;
optional string address2 = 2;
required string city = 3;
required string state = 4;
required fixed32 zip = 5;
}
extensions 100 to 199;
}
message TestInteropEmployeeId {
required string number = 1;
}
extend TestInteropPerson {
required TestInteropEmployeeId employee_id = 126;
}
message TestMissingFieldsA {
required string name = 1;
required int32 id = 2;
optional string email = 3;
message SubA {
required int32 count = 5;
repeated string values = 6;
}
optional SubA testA = 11;
}
message TestMissingFieldsB {
required string name = 1;
required int32 id = 2;
optional string website = 4;
message SubB {
repeated string values = 7;
}
optional SubB testB = 12;
}

@ -0,0 +1,61 @@
// Additional options required for C# generation. File from copyright
// line onwards is as per original distribution.
import "google/protobuf/csharp_options.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.TestProtos";
option (google.protobuf.csharp_file_options).umbrella_classname = "UnitTestExtrasLiteProtoFile";
package protobuf_unittest_extra;
option optimize_for = LITE_RUNTIME;
option java_package = "com.google.protobuf";
message TestRequiredLite {
required int32 d = 1;
required ExtraEnum en = 2 [default = DEFAULT];
}
enum ExtraEnum {
DEFAULT = 10;
EXLITE_FOO = 7;
EXLITE_BAR = 8;
EXLITE_BAZ = 9;
}
message TestInteropPersonLite {
required string name = 1;
required int32 id = 2;
optional string email = 3;
repeated int32 codes = 10 [packed=true];
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
message PhoneNumber {
required string number = 1;
optional PhoneType type = 2 [default = HOME];
}
repeated PhoneNumber phone = 4;
repeated group Addresses = 5 {
required string address = 1;
optional string address2 = 2;
required string city = 3;
required string state = 4;
required fixed32 zip = 5;
}
extensions 100 to 199;
}
message TestInteropEmployeeIdLite {
required string number = 1;
}
extend TestInteropPersonLite {
required TestInteropEmployeeIdLite employee_id_lite = 126;
}

@ -247,13 +247,31 @@ message FileOptions {
// Generated classes can be optimized for speed or code size.
enum OptimizeMode {
SPEED = 1; // Generate complete code for parsing, serialization, etc.
CODE_SIZE = 2; // Use ReflectionOps to implement these methods.
SPEED = 1; // Generate complete code for parsing, serialization,
// etc.
CODE_SIZE = 2; // Use ReflectionOps to implement these methods.
LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime.
}
optional OptimizeMode optimize_for = 9 [default=SPEED];
// Should generic services be generated in each language? "Generic" services
// are not specific to any particular RPC system. They are generated by the
// main code generators in each language (without additional plugins).
// Generic services were the only kind of service generation supported by
// early versions of proto2.
//
// Generic services are now considered deprecated in favor of using plugins
// that generate code specific to your particular RPC system. If you are
// using such a plugin, set these to false. In the future, we may change
// the default to false, so if you explicitly want generic services, you
// should explicitly set these to true.
optional bool cc_generic_services = 16 [default=true];
optional bool java_generic_services = 17 [default=true];
optional bool py_generic_services = 18 [default=true];
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
@ -282,6 +300,11 @@ message MessageOptions {
// the protocol compiler.
optional bool message_set_wire_format = 1 [default=false];
// Disables the generation of the standard "descriptor()" accessor, which can
// conflict with a field of the same name. This is meant to make migration
// from proto1 easier; new code should avoid fields named "descriptor".
optional bool no_standard_descriptor_accessor = 2 [default=false];
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;
@ -294,8 +317,11 @@ message FieldOptions {
// representation of the field than it normally would. See the specific
// options below. This option is not yet implemented in the open source
// release -- sorry, we'll try to include it in a future version!
optional CType ctype = 1;
optional CType ctype = 1 [default = STRING];
enum CType {
// Default mode.
STRING = 0;
CORD = 1;
STRING_PIECE = 2;
@ -306,12 +332,13 @@ message FieldOptions {
// a single length-delimited blob.
optional bool packed = 2;
// Is this field deprecated?
// Depending on the target platform, this can emit Deprecated annotations
// for accessors, or it will be completely ignored; in the very least, this
// is a formalization for deprecating fields.
optional bool deprecated = 3 [default=false];
// EXPERIMENTAL. DO NOT USE.
// For "map" fields, the name of the field in the enclosed type that
// is the key for this map. For example, suppose we have:
@ -334,6 +361,7 @@ message FieldOptions {
}
message EnumOptions {
// The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999;

@ -161,6 +161,10 @@ message TestAllTypes {
optional string default_cord = 85 [ctype=CORD,default="123"];
}
message TestDeprecatedFields {
optional int32 deprecated_int32 = 1 [deprecated=true];
}
// Define these after TestAllTypes to make sure the compiler can handle
// that.
message ForeignMessage {
@ -275,6 +279,14 @@ extend TestAllExtensions {
optional string default_cord_extension = 85 [ctype=CORD, default="123"];
}
message TestNestedExtension {
extend TestAllExtensions {
// Check for bug where string extensions declared in tested scope did not
// compile.
optional string test = 1002 [default="test"];
}
}
// We have separate messages for testing required fields because it's
// annoying to have to fill in required fields in TestProto in order to
// do anything with it. Note that we don't need to test every type of
@ -346,6 +358,12 @@ message TestEmptyMessageWithExtensions {
extensions 1 to max;
}
message TestMultipleExtensionRanges {
extensions 42;
extensions 4143 to 4243;
extensions 65536 to max;
}
// Test that really large tag numbers don't break anything.
message TestReallyLargeTagNumber {
// The largest possible tag number is 2^28 - 1, since the wire format uses
@ -370,13 +388,14 @@ message TestMutualRecursionB {
}
// Test that groups have disjoint field numbers from their siblings and
// parents. This is NOT possible in proto1; only proto2. When outputting
// proto1, the dup fields should be dropped.
message TestDupFieldNumber {
optional int32 a = 1;
optional group Foo = 2 { optional int32 a = 1; }
optional group Bar = 3 { optional int32 a = 1; }
}
// parents. This is NOT possible in proto1; only proto2. When attempting
// to compile with proto1, this will emit an error; so we only include it
// in protobuf_unittest_proto.
message TestDupFieldNumber { // NO_PROTO1
optional int32 a = 1; // NO_PROTO1
optional group Foo = 2 { optional int32 a = 1; } // NO_PROTO1
optional group Bar = 3 { optional int32 a = 1; } // NO_PROTO1
} // NO_PROTO1
// Needed for a Python test.
@ -456,8 +475,37 @@ message TestExtremeDefaultValues {
// the UTF-8 text directly into this text file rather than escape it, but
// lots of people use editors that would be confused by this.)
optional string utf8_string = 6 [default = "\341\210\264"];
// Tests for single-precision floating-point values.
optional float zero_float = 7 [default = 0];
optional float one_float = 8 [default = 1];
optional float small_float = 9 [default = 1.5];
optional float negative_one_float = 10 [default = -1];
optional float negative_float = 11 [default = -1.5];
// Using exponents
optional float large_float = 12 [default = 2E8];
optional float small_negative_float = 13 [default = -8e-28];
// Text for nonfinite floating-point values.
optional double inf_double = 14 [default = inf];
optional double neg_inf_double = 15 [default = -inf];
optional double nan_double = 16 [default = nan];
optional float inf_float = 17 [default = inf];
optional float neg_inf_float = 18 [default = -inf];
optional float nan_float = 19 [default = nan];
}
// Test String and Bytes: string is for valid UTF-8 strings
message OneString {
optional string data = 1;
}
message OneBytes {
optional bytes data = 1;
}
// Test messages for packed fields
message TestPackedTypes {
repeated int32 packed_int32 = 90 [packed = true];
repeated int64 packed_int64 = 91 [packed = true];
@ -475,6 +523,25 @@ message TestPackedTypes {
repeated ForeignEnum packed_enum = 103 [packed = true];
}
// A message with the same fields as TestPackedTypes, but without packing. Used
// to test packed <-> unpacked wire compatibility.
message TestUnpackedTypes {
repeated int32 unpacked_int32 = 90 [packed = false];
repeated int64 unpacked_int64 = 91 [packed = false];
repeated uint32 unpacked_uint32 = 92 [packed = false];
repeated uint64 unpacked_uint64 = 93 [packed = false];
repeated sint32 unpacked_sint32 = 94 [packed = false];
repeated sint64 unpacked_sint64 = 95 [packed = false];
repeated fixed32 unpacked_fixed32 = 96 [packed = false];
repeated fixed64 unpacked_fixed64 = 97 [packed = false];
repeated sfixed32 unpacked_sfixed32 = 98 [packed = false];
repeated sfixed64 unpacked_sfixed64 = 99 [packed = false];
repeated float unpacked_float = 100 [packed = false];
repeated double unpacked_double = 101 [packed = false];
repeated bool unpacked_bool = 102 [packed = false];
repeated ForeignEnum unpacked_enum = 103 [packed = false];
}
message TestPackedExtensions {
extensions 1 to max;
}
@ -496,6 +563,47 @@ extend TestPackedExtensions {
repeated ForeignEnum packed_enum_extension = 103 [packed = true];
}
// Used by ExtensionSetTest/DynamicExtensions. The test actually builds
// a set of extensions to TestAllExtensions dynamically, based on the fields
// of this message type.
message TestDynamicExtensions {
enum DynamicEnumType {
DYNAMIC_FOO = 2200;
DYNAMIC_BAR = 2201;
DYNAMIC_BAZ = 2202;
}
message DynamicMessageType {
optional int32 dynamic_field = 2100;
}
optional fixed32 scalar_extension = 2000;
optional ForeignEnum enum_extension = 2001;
optional DynamicEnumType dynamic_enum_extension = 2002;
optional ForeignMessage message_extension = 2003;
optional DynamicMessageType dynamic_message_extension = 2004;
repeated string repeated_extension = 2005;
repeated sint32 packed_extension = 2006 [packed = true];
}
message TestRepeatedScalarDifferentTagSizes {
// Parsing repeated fixed size values used to fail. This message needs to be
// used in order to get a tag of the right size; all of the repeated fields
// in TestAllTypes didn't trigger the check.
repeated fixed32 repeated_fixed32 = 12;
// Check for a varint type, just for good measure.
repeated int32 repeated_int32 = 13;
// These have two-byte tags.
repeated fixed64 repeated_fixed64 = 2046;
repeated int64 repeated_int64 = 2047;
// Three byte tags.
repeated float repeated_float = 262142;
repeated uint64 repeated_uint64 = 262143;
}
// Test that RPC services work.
message FooRequest {}
message FooResponse {}

@ -72,7 +72,9 @@ extend google.protobuf.EnumOptions {
optional sfixed32 enum_opt1 = 7753576;
}
// TODO(benjy): Test options on enum values when the parser supports them.
extend google.protobuf.EnumValueOptions {
optional int32 enum_value_opt1 = 1560678;
}
extend google.protobuf.ServiceOptions {
optional sint64 service_opt1 = 7887650;
@ -101,7 +103,7 @@ message TestMessageWithCustomOptions {
option (enum_opt1) = -789;
ANENUM_VAL1 = 1;
ANENUM_VAL2 = 2;
ANENUM_VAL2 = 2 [(enum_value_opt1) = 123];
}
}
@ -208,6 +210,8 @@ message SettingRealsFromNegativeInts {
message ComplexOptionType1 {
optional int32 foo = 1;
optional int32 foo2 = 2;
optional int32 foo3 = 3;
extensions 100 to max;
}

@ -0,0 +1,43 @@
// Additional options required for C# generation. File from copyright
// line onwards is as per original distribution.
import "google/protobuf/csharp_options.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.TestProtos";
option (google.protobuf.csharp_file_options).umbrella_classname = "UnitTestEmptyProtoFile";
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// 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.
// Author: kenton@google.com (Kenton Varda)
// Based on original Protocol Buffers design by
// Sanjay Ghemawat, Jeff Dean, and others.
//
// This file intentionally left blank. (At one point this wouldn't compile
// correctly.)

File diff suppressed because it is too large Load Diff

@ -0,0 +1,55 @@
// Additional options required for C# generation. File from copyright
// line onwards is as per original distribution.
import "google/protobuf/csharp_options.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.TestProtos";
option (google.protobuf.csharp_file_options).umbrella_classname = "UnitTestImportLiteProtoFile";
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// 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.
// Author: kenton@google.com (Kenton Varda)
//
// This is like unittest_import.proto but with optimize_for = LITE_RUNTIME.
package protobuf_unittest_import;
option optimize_for = LITE_RUNTIME;
option java_package = "com.google.protobuf";
message ImportMessageLite {
optional int32 d = 1;
}
enum ImportEnumLite {
IMPORT_LITE_FOO = 7;
IMPORT_LITE_BAR = 8;
IMPORT_LITE_BAZ = 9;
}

@ -0,0 +1,318 @@
// Additional options required for C# generation. File from copyright
// line onwards is as per original distribution.
import "google/protobuf/csharp_options.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.TestProtos";
option (google.protobuf.csharp_file_options).umbrella_classname = "UnitTestLiteProtoFile";
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// 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.
// Author: kenton@google.com (Kenton Varda)
//
// This is like unittest.proto but with optimize_for = LITE_RUNTIME.
package protobuf_unittest;
import "google/protobuf/unittest_import_lite.proto";
option optimize_for = LITE_RUNTIME;
option java_package = "com.google.protobuf";
// Same as TestAllTypes but with the lite runtime.
message TestAllTypesLite {
message NestedMessage {
optional int32 bb = 1;
}
enum NestedEnum {
FOO = 1;
BAR = 2;
BAZ = 3;
}
// Singular
optional int32 optional_int32 = 1;
optional int64 optional_int64 = 2;
optional uint32 optional_uint32 = 3;
optional uint64 optional_uint64 = 4;
optional sint32 optional_sint32 = 5;
optional sint64 optional_sint64 = 6;
optional fixed32 optional_fixed32 = 7;
optional fixed64 optional_fixed64 = 8;
optional sfixed32 optional_sfixed32 = 9;
optional sfixed64 optional_sfixed64 = 10;
optional float optional_float = 11;
optional double optional_double = 12;
optional bool optional_bool = 13;
optional string optional_string = 14;
optional bytes optional_bytes = 15;
optional group OptionalGroup = 16 {
optional int32 a = 17;
}
optional NestedMessage optional_nested_message = 18;
optional ForeignMessageLite optional_foreign_message = 19;
optional protobuf_unittest_import.ImportMessageLite
optional_import_message = 20;
optional NestedEnum optional_nested_enum = 21;
optional ForeignEnumLite optional_foreign_enum = 22;
optional protobuf_unittest_import.ImportEnumLite optional_import_enum = 23;
optional string optional_string_piece = 24 [ctype=STRING_PIECE];
optional string optional_cord = 25 [ctype=CORD];
// Repeated
repeated int32 repeated_int32 = 31;
repeated int64 repeated_int64 = 32;
repeated uint32 repeated_uint32 = 33;
repeated uint64 repeated_uint64 = 34;
repeated sint32 repeated_sint32 = 35;
repeated sint64 repeated_sint64 = 36;
repeated fixed32 repeated_fixed32 = 37;
repeated fixed64 repeated_fixed64 = 38;
repeated sfixed32 repeated_sfixed32 = 39;
repeated sfixed64 repeated_sfixed64 = 40;
repeated float repeated_float = 41;
repeated double repeated_double = 42;
repeated bool repeated_bool = 43;
repeated string repeated_string = 44;
repeated bytes repeated_bytes = 45;
repeated group RepeatedGroup = 46 {
optional int32 a = 47;
}
repeated NestedMessage repeated_nested_message = 48;
repeated ForeignMessageLite repeated_foreign_message = 49;
repeated protobuf_unittest_import.ImportMessageLite
repeated_import_message = 50;
repeated NestedEnum repeated_nested_enum = 51;
repeated ForeignEnumLite repeated_foreign_enum = 52;
repeated protobuf_unittest_import.ImportEnumLite repeated_import_enum = 53;
repeated string repeated_string_piece = 54 [ctype=STRING_PIECE];
repeated string repeated_cord = 55 [ctype=CORD];
// Singular with defaults
optional int32 default_int32 = 61 [default = 41 ];
optional int64 default_int64 = 62 [default = 42 ];
optional uint32 default_uint32 = 63 [default = 43 ];
optional uint64 default_uint64 = 64 [default = 44 ];
optional sint32 default_sint32 = 65 [default = -45 ];
optional sint64 default_sint64 = 66 [default = 46 ];
optional fixed32 default_fixed32 = 67 [default = 47 ];
optional fixed64 default_fixed64 = 68 [default = 48 ];
optional sfixed32 default_sfixed32 = 69 [default = 49 ];
optional sfixed64 default_sfixed64 = 70 [default = -50 ];
optional float default_float = 71 [default = 51.5 ];
optional double default_double = 72 [default = 52e3 ];
optional bool default_bool = 73 [default = true ];
optional string default_string = 74 [default = "hello"];
optional bytes default_bytes = 75 [default = "world"];
optional NestedEnum default_nested_enum = 81 [default = BAR];
optional ForeignEnumLite default_foreign_enum = 82
[default = FOREIGN_LITE_BAR];
optional protobuf_unittest_import.ImportEnumLite
default_import_enum = 83 [default = IMPORT_LITE_BAR];
optional string default_string_piece = 84 [ctype=STRING_PIECE,default="abc"];
optional string default_cord = 85 [ctype=CORD,default="123"];
}
message ForeignMessageLite {
optional int32 c = 1;
}
enum ForeignEnumLite {
FOREIGN_LITE_FOO = 4;
FOREIGN_LITE_BAR = 5;
FOREIGN_LITE_BAZ = 6;
}
message TestPackedTypesLite {
repeated int32 packed_int32 = 90 [packed = true];
repeated int64 packed_int64 = 91 [packed = true];
repeated uint32 packed_uint32 = 92 [packed = true];
repeated uint64 packed_uint64 = 93 [packed = true];
repeated sint32 packed_sint32 = 94 [packed = true];
repeated sint64 packed_sint64 = 95 [packed = true];
repeated fixed32 packed_fixed32 = 96 [packed = true];
repeated fixed64 packed_fixed64 = 97 [packed = true];
repeated sfixed32 packed_sfixed32 = 98 [packed = true];
repeated sfixed64 packed_sfixed64 = 99 [packed = true];
repeated float packed_float = 100 [packed = true];
repeated double packed_double = 101 [packed = true];
repeated bool packed_bool = 102 [packed = true];
repeated ForeignEnumLite packed_enum = 103 [packed = true];
}
message TestAllExtensionsLite {
extensions 1 to max;
}
extend TestAllExtensionsLite {
// Singular
optional int32 optional_int32_extension_lite = 1;
optional int64 optional_int64_extension_lite = 2;
optional uint32 optional_uint32_extension_lite = 3;
optional uint64 optional_uint64_extension_lite = 4;
optional sint32 optional_sint32_extension_lite = 5;
optional sint64 optional_sint64_extension_lite = 6;
optional fixed32 optional_fixed32_extension_lite = 7;
optional fixed64 optional_fixed64_extension_lite = 8;
optional sfixed32 optional_sfixed32_extension_lite = 9;
optional sfixed64 optional_sfixed64_extension_lite = 10;
optional float optional_float_extension_lite = 11;
optional double optional_double_extension_lite = 12;
optional bool optional_bool_extension_lite = 13;
optional string optional_string_extension_lite = 14;
optional bytes optional_bytes_extension_lite = 15;
optional group OptionalGroup_extension_lite = 16 {
optional int32 a = 17;
}
optional TestAllTypesLite.NestedMessage optional_nested_message_extension_lite
= 18;
optional ForeignMessageLite optional_foreign_message_extension_lite = 19;
optional protobuf_unittest_import.ImportMessageLite
optional_import_message_extension_lite = 20;
optional TestAllTypesLite.NestedEnum optional_nested_enum_extension_lite = 21;
optional ForeignEnumLite optional_foreign_enum_extension_lite = 22;
optional protobuf_unittest_import.ImportEnumLite
optional_import_enum_extension_lite = 23;
optional string optional_string_piece_extension_lite = 24
[ctype=STRING_PIECE];
optional string optional_cord_extension_lite = 25 [ctype=CORD];
// Repeated
repeated int32 repeated_int32_extension_lite = 31;
repeated int64 repeated_int64_extension_lite = 32;
repeated uint32 repeated_uint32_extension_lite = 33;
repeated uint64 repeated_uint64_extension_lite = 34;
repeated sint32 repeated_sint32_extension_lite = 35;
repeated sint64 repeated_sint64_extension_lite = 36;
repeated fixed32 repeated_fixed32_extension_lite = 37;
repeated fixed64 repeated_fixed64_extension_lite = 38;
repeated sfixed32 repeated_sfixed32_extension_lite = 39;
repeated sfixed64 repeated_sfixed64_extension_lite = 40;
repeated float repeated_float_extension_lite = 41;
repeated double repeated_double_extension_lite = 42;
repeated bool repeated_bool_extension_lite = 43;
repeated string repeated_string_extension_lite = 44;
repeated bytes repeated_bytes_extension_lite = 45;
repeated group RepeatedGroup_extension_lite = 46 {
optional int32 a = 47;
}
repeated TestAllTypesLite.NestedMessage repeated_nested_message_extension_lite
= 48;
repeated ForeignMessageLite repeated_foreign_message_extension_lite = 49;
repeated protobuf_unittest_import.ImportMessageLite
repeated_import_message_extension_lite = 50;
repeated TestAllTypesLite.NestedEnum repeated_nested_enum_extension_lite = 51;
repeated ForeignEnumLite repeated_foreign_enum_extension_lite = 52;
repeated protobuf_unittest_import.ImportEnumLite
repeated_import_enum_extension_lite = 53;
repeated string repeated_string_piece_extension_lite = 54
[ctype=STRING_PIECE];
repeated string repeated_cord_extension_lite = 55 [ctype=CORD];
// Singular with defaults
optional int32 default_int32_extension_lite = 61 [default = 41 ];
optional int64 default_int64_extension_lite = 62 [default = 42 ];
optional uint32 default_uint32_extension_lite = 63 [default = 43 ];
optional uint64 default_uint64_extension_lite = 64 [default = 44 ];
optional sint32 default_sint32_extension_lite = 65 [default = -45 ];
optional sint64 default_sint64_extension_lite = 66 [default = 46 ];
optional fixed32 default_fixed32_extension_lite = 67 [default = 47 ];
optional fixed64 default_fixed64_extension_lite = 68 [default = 48 ];
optional sfixed32 default_sfixed32_extension_lite = 69 [default = 49 ];
optional sfixed64 default_sfixed64_extension_lite = 70 [default = -50 ];
optional float default_float_extension_lite = 71 [default = 51.5 ];
optional double default_double_extension_lite = 72 [default = 52e3 ];
optional bool default_bool_extension_lite = 73 [default = true ];
optional string default_string_extension_lite = 74 [default = "hello"];
optional bytes default_bytes_extension_lite = 75 [default = "world"];
optional TestAllTypesLite.NestedEnum
default_nested_enum_extension_lite = 81 [default = BAR];
optional ForeignEnumLite
default_foreign_enum_extension_lite = 82 [default = FOREIGN_LITE_BAR];
optional protobuf_unittest_import.ImportEnumLite
default_import_enum_extension_lite = 83 [default = IMPORT_LITE_BAR];
optional string default_string_piece_extension_lite = 84 [ctype=STRING_PIECE,
default="abc"];
optional string default_cord_extension_lite = 85 [ctype=CORD, default="123"];
}
message TestPackedExtensionsLite {
extensions 1 to max;
}
extend TestPackedExtensionsLite {
repeated int32 packed_int32_extension_lite = 90 [packed = true];
repeated int64 packed_int64_extension_lite = 91 [packed = true];
repeated uint32 packed_uint32_extension_lite = 92 [packed = true];
repeated uint64 packed_uint64_extension_lite = 93 [packed = true];
repeated sint32 packed_sint32_extension_lite = 94 [packed = true];
repeated sint64 packed_sint64_extension_lite = 95 [packed = true];
repeated fixed32 packed_fixed32_extension_lite = 96 [packed = true];
repeated fixed64 packed_fixed64_extension_lite = 97 [packed = true];
repeated sfixed32 packed_sfixed32_extension_lite = 98 [packed = true];
repeated sfixed64 packed_sfixed64_extension_lite = 99 [packed = true];
repeated float packed_float_extension_lite = 100 [packed = true];
repeated double packed_double_extension_lite = 101 [packed = true];
repeated bool packed_bool_extension_lite = 102 [packed = true];
repeated ForeignEnumLite packed_enum_extension_lite = 103 [packed = true];
}
message TestNestedExtensionLite {
extend TestAllExtensionsLite {
optional int32 nested_extension = 12345;
}
}
// Test that deprecated fields work. We only verify that they compile (at one
// point this failed).
message TestDeprecatedLite {
optional int32 deprecated_field = 1 [deprecated = true];
}

@ -0,0 +1,49 @@
// Additional options required for C# generation. File from copyright
// line onwards is as per original distribution.
import "google/protobuf/csharp_options.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.TestProtos";
option (google.protobuf.csharp_file_options).umbrella_classname = "UnitTestLiteImportNonLiteProtoFile";
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// 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.
// Author: kenton@google.com (Kenton Varda)
//
// Tests that a "lite" message can import a regular message.
package protobuf_unittest;
import "google/protobuf/unittest.proto";
option optimize_for = LITE_RUNTIME;
message TestLiteImportsNonlite {
optional TestAllTypes message = 1;
}

@ -0,0 +1,60 @@
// Additional options required for C# generation. File from copyright
// line onwards is as per original distribution.
import "google/protobuf/csharp_options.proto";
option (google.protobuf.csharp_file_options).namespace = "Google.ProtocolBuffers.TestProtos.NoGenericService";
option (google.protobuf.csharp_file_options).umbrella_classname = "UnitTestNoGenericServicesProtoFile";
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// 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.
// Author: kenton@google.com (Kenton Varda)
package google.protobuf.no_generic_services_test;
option cc_generic_services = false;
option java_generic_services = false;
option py_generic_services = false;
message TestMessage {
optional int32 a = 1;
extensions 1000 to max;
}
enum TestEnum {
FOO = 1;
}
extend TestMessage {
optional int32 test_extension = 1000;
}
service TestService {
rpc Foo(TestMessage) returns(TestMessage);
}

@ -1,4 +1,4 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// Generated by ProtoGen, Version=0.9.0.0, Culture=neutral, PublicKeyToken=8fd7408b07f8d2cd. DO NOT EDIT!
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;

@ -78,7 +78,7 @@
<ItemGroup>
<Reference Include="nunit.framework, Version=2.2.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\nunit.framework.dll</HintPath>
<HintPath>..\..\lib\NUnit 2.2.8.0\nunit.framework.dll</HintPath>
</Reference>
<Reference Include="Rhino.Mocks, Version=3.5.0.2, Culture=neutral, PublicKeyToken=0b3305902db7183f, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>

@ -88,10 +88,12 @@ namespace Google.ProtocolBuffers.ProtoGen {
// TODO(jonskeet): Make a more efficient way of doing this
writer.WriteLine("int rawValue = input.ReadEnum();");
writer.WriteLine("if (!global::System.Enum.IsDefined(typeof({0}), rawValue)) {{", TypeName);
writer.WriteLine(" if (unknownFields == null) {"); // First unknown field - create builder now
writer.WriteLine(" unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);");
writer.WriteLine(" }");
writer.WriteLine(" unknownFields.MergeVarintField({0}, (ulong) rawValue);", Number);
if (!UseLiteRuntime) {
writer.WriteLine(" if (unknownFields == null) {"); // First unknown field - create builder now
writer.WriteLine(" unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);");
writer.WriteLine(" }");
writer.WriteLine(" unknownFields.MergeVarintField({0}, (ulong) rawValue);", Number);
}
writer.WriteLine("} else {");
writer.WriteLine(" {0} = ({1}) rawValue;", PropertyName, TypeName);
writer.WriteLine("}");
@ -106,7 +108,19 @@ namespace Google.ProtocolBuffers.ProtoGen {
public void GenerateSerializedSizeCode(TextGenerator writer) {
writer.WriteLine("if (Has{0}) {{", PropertyName);
writer.WriteLine(" size += pb::CodedOutputStream.ComputeEnumSize({0}, (int) {1});", Number, PropertyName);
writer.WriteLine("}");
writer.WriteLine("}");
}
public override void WriteHash(TextGenerator writer) {
writer.WriteLine("if (has{0}) hash ^= {1}_.GetHashCode();", PropertyName, Name);
}
public override void WriteEquals(TextGenerator writer) {
writer.WriteLine("if (has{0} != other.has{0} || (has{0} && !{1}_.Equals(other.{1}_))) return false;", PropertyName, Name);
}
public override void WriteToString(TextGenerator writer) {
writer.WriteLine("PrintField(\"{0}\", has{1}, {2}_, writer);", Descriptor.Name, PropertyName, Name);
}
}
}

@ -32,16 +32,20 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Globalization;
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.ProtoGen {
internal class ExtensionGenerator : SourceGeneratorBase<FieldDescriptor>, ISourceGenerator {
internal class ExtensionGenerator : FieldGeneratorBase, ISourceGenerator {
private readonly string extends;
private readonly string scope;
private readonly string type;
private readonly string name;
internal ExtensionGenerator(FieldDescriptor descriptor) : base(descriptor) {
internal ExtensionGenerator(FieldDescriptor descriptor)
: base(descriptor) {
if (Descriptor.ExtensionScope != null) {
scope = GetClassName(Descriptor.ExtensionScope);
} else {
@ -58,14 +62,24 @@ namespace Google.ProtocolBuffers.ProtoGen {
type = DescriptorUtil.GetMappedTypeName(Descriptor.MappedType);
break;
}
extends = GetClassName(Descriptor.ContainingType);
name = Descriptor.CSharpOptions.PropertyName;
}
public void Generate(TextGenerator writer) {
writer.WriteLine ("public const int {0} = {1};", GetFieldConstantName(Descriptor), Descriptor.FieldNumber);
if (Descriptor.IsRepeated) {
if (!Descriptor.IsCLSCompliant && Descriptor.File.CSharpOptions.ClsCompliance)
{
writer.WriteLine("public const int {0} = {1};", GetFieldConstantName(Descriptor), Descriptor.FieldNumber);
if (UseLiteRuntime) {
if (Descriptor.MappedType == MappedType.Message && Descriptor.MessageType.Options.MessageSetWireFormat) {
throw new ArgumentException("option message_set_wire_format = true; is not supported in Lite runtime extensions.");
}
if (!Descriptor.IsCLSCompliant && Descriptor.File.CSharpOptions.ClsCompliance) {
writer.WriteLine("[global::System.CLSCompliant(false)]");
}
writer.WriteLine("{0} static pb::{4}<{1}, {2}> {3};", ClassAccessLevel, extends, type, name,
Descriptor.IsRepeated ? "GeneratedRepeatExtensionLite" : "GeneratedExtensionLite");
} else if (Descriptor.IsRepeated) {
if (!Descriptor.IsCLSCompliant && Descriptor.File.CSharpOptions.ClsCompliance) {
writer.WriteLine("[global::System.CLSCompliant(false)]");
}
writer.WriteLine("{0} static pb::GeneratedExtensionBase<scg::IList<{1}>> {2};", ClassAccessLevel, type, name);
@ -78,7 +92,27 @@ namespace Google.ProtocolBuffers.ProtoGen {
}
internal void GenerateStaticVariableInitializers(TextGenerator writer) {
if (Descriptor.IsRepeated) {
if (UseLiteRuntime) {
writer.WriteLine("{0}.{1} = ", scope, name);
writer.Indent();
writer.WriteLine("new pb::{0}<{1}, {2}>(", Descriptor.IsRepeated ? "GeneratedRepeatExtensionLite" : "GeneratedExtensionLite", extends, type);
writer.Indent();
writer.WriteLine("\"{0}\",", Descriptor.FullName);
writer.WriteLine("{0}.DefaultInstance,", extends);
if(!Descriptor.IsRepeated)
writer.WriteLine("{0},", Descriptor.HasDefaultValue ? DefaultValue : IsNullableType ? "null" : "default(" + type + ")");
writer.WriteLine("{0},", (Descriptor.MappedType == MappedType.Message) ? type + ".DefaultInstance" : "null");
writer.WriteLine("{0},", (Descriptor.MappedType == MappedType.Enum) ? "new EnumLiteMap<" + type + ">()" : "null");
writer.WriteLine("{0}.{1}FieldNumber,", scope, name);
writer.Write("pbd::FieldType.{0}", Descriptor.FieldType);
if (Descriptor.IsRepeated) {
writer.WriteLine(",");
writer.Write(Descriptor.IsPacked ? "true" : "false");
}
writer.Outdent();
writer.WriteLine(");");
writer.Outdent();
} else if (Descriptor.IsRepeated) {
writer.WriteLine("{0}.{1} = pb::GeneratedRepeatExtension<{2}>.CreateInstance({0}.Descriptor.Extensions[{3}]);", scope, name, type, Descriptor.Index);
} else {
writer.WriteLine("{0}.{1} = pb::GeneratedSingleExtension<{2}>.CreateInstance({0}.Descriptor.Extensions[{3}]);", scope, name, type, Descriptor.Index);
@ -88,5 +122,14 @@ namespace Google.ProtocolBuffers.ProtoGen {
internal void GenerateExtensionRegistrationCode(TextGenerator writer) {
writer.WriteLine("registry.Add({0}.{1});", scope, name);
}
public override void WriteHash(TextGenerator writer) {
}
public override void WriteEquals(TextGenerator writer) {
}
public override void WriteToString(TextGenerator writer) {
}
}
}

@ -42,6 +42,10 @@ namespace Google.ProtocolBuffers.ProtoGen {
: base(descriptor) {
}
public abstract void WriteHash(TextGenerator writer);
public abstract void WriteEquals(TextGenerator writer);
public abstract void WriteToString(TextGenerator writer);
private static bool AllPrintableAscii(string text) {
foreach (char c in text) {
if (c < 0x20 || c > 0x7e) {
@ -51,6 +55,7 @@ namespace Google.ProtocolBuffers.ProtoGen {
return true;
}
/// <remarks>Copy exists in ExtensionGenerator.cs</remarks>
protected string DefaultValue {
get {
string suffix = "";
@ -72,11 +77,30 @@ namespace Google.ProtocolBuffers.ProtoGen {
case FieldType.UInt32:
case FieldType.UInt64:
case FieldType.Fixed32:
case FieldType.Fixed64:
case FieldType.Fixed64:
{
// The simple Object.ToString converts using the current culture.
// We want to always use the invariant culture so it's predictable.
IConvertible value = (IConvertible) Descriptor.DefaultValue;
//a few things that must be handled explicitly
if (Descriptor.FieldType == FieldType.Double && value is double) {
if (double.IsNaN((double) value))
return "double.NaN";
if (double.IsPositiveInfinity((double) value))
return "double.PositiveInfinity";
if (double.IsNegativeInfinity((double) value))
return "double.NegativeInfinity";
}
else if (Descriptor.FieldType == FieldType.Float && value is float) {
if (float.IsNaN((float)value))
return "float.NaN";
if (float.IsPositiveInfinity((float)value))
return "float.PositiveInfinity";
if (float.IsNegativeInfinity((float)value))
return "float.NegativeInfinity";
}
return value.ToString(CultureInfo.InvariantCulture) + suffix;
}
case FieldType.Bool:
return (bool) Descriptor.DefaultValue ? "true" : "false";
@ -84,6 +108,10 @@ namespace Google.ProtocolBuffers.ProtoGen {
if (!Descriptor.HasDefaultValue) {
return "pb::ByteString.Empty";
}
if (UseLiteRuntime && Descriptor.DefaultValue is ByteString) {
string temp = Convert.ToBase64String(((ByteString)Descriptor.DefaultValue).ToByteArray());
return String.Format("ByteString.FromBase64(\"{0}\")", temp);
}
return string.Format("(pb::ByteString) {0}.Descriptor.Fields[{1}].DefaultValue", GetClassName(Descriptor.ContainingType), Descriptor.Index);
case FieldType.String:
if (AllPrintableAscii(Descriptor.Proto.DefaultValue)) {
@ -95,6 +123,10 @@ namespace Google.ProtocolBuffers.ProtoGen {
.Replace("\"", "\\\"")
+ "\"";
}
if (UseLiteRuntime && Descriptor.DefaultValue is String) {
string temp = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes((String)Descriptor.DefaultValue));
return String.Format("ByteString.FromBase64(\"{0}\").ToStringUtf8()", temp);
}
return string.Format("(string) {0}.Descriptor.Fields[{1}].DefaultValue", GetClassName(Descriptor.ContainingType), Descriptor.Index);
case FieldType.Enum:
return TypeName + "." + ((EnumValueDescriptor) Descriptor.DefaultValue).Name;

@ -38,11 +38,5 @@ namespace Google.ProtocolBuffers.ProtoGen {
/// Helpers to resolve class names etc.
/// </summary>
internal static class Helpers {
internal static void WriteNamespaces(TextGenerator writer) {
writer.WriteLine("using pb = global::Google.ProtocolBuffers;");
writer.WriteLine("using pbc = global::Google.ProtocolBuffers.Collections;");
writer.WriteLine("using pbd = global::Google.ProtocolBuffers.Descriptors;");
writer.WriteLine("using scg = global::System.Collections.Generic;");
}
}
}

@ -41,5 +41,9 @@ namespace Google.ProtocolBuffers.ProtoGen {
void GenerateParsingCode(TextGenerator writer);
void GenerateSerializationCode(TextGenerator writer);
void GenerateSerializedSizeCode(TextGenerator writer);
void WriteHash(TextGenerator writer);
void WriteEquals(TextGenerator writer);
void WriteToString(TextGenerator writer);
}
}

@ -125,5 +125,18 @@ namespace Google.ProtocolBuffers.ProtoGen {
MessageOrGroup, Number, PropertyName);
writer.WriteLine("}");
}
public override void WriteHash(TextGenerator writer) {
writer.WriteLine("if (has{0}) hash ^= {1}_.GetHashCode();", PropertyName, Name);
}
public override void WriteEquals(TextGenerator writer) {
writer.WriteLine("if (has{0} != other.has{0} || (has{0} && !{1}_.Equals(other.{1}_))) return false;", PropertyName, Name);
}
public override void WriteToString(TextGenerator writer) {
writer.WriteLine("PrintField(\"{2}\", has{0}, {1}_, writer);", PropertyName, Name,
Descriptor.FieldType == FieldType.Group ? Descriptor.MessageType.Name : Descriptor.Name);
}
}
}

@ -32,6 +32,7 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Generic;
using Google.ProtocolBuffers.DescriptorProtos;
using Google.ProtocolBuffers.Descriptors;
@ -69,12 +70,13 @@ namespace Google.ProtocolBuffers.ProtoGen {
string identifier = GetUniqueFileScopeIdentifier(Descriptor);
// The descriptor for this type.
string access = Descriptor.File.CSharpOptions.NestClasses ? "private" : "internal";
writer.WriteLine("{0} static pbd::MessageDescriptor internal__{1}__Descriptor;", access, identifier);
writer.WriteLine("{0} static pb::FieldAccess.FieldAccessorTable<{1}, {1}.Builder> internal__{2}__FieldAccessorTable;",
access, FullClassName, identifier);
if (!UseLiteRuntime) {
// The descriptor for this type.
string access = Descriptor.File.CSharpOptions.NestClasses ? "private" : "internal";
writer.WriteLine("{0} static pbd::MessageDescriptor internal__{1}__Descriptor;", access, identifier);
writer.WriteLine("{0} static pb::FieldAccess.FieldAccessorTable<{1}, {1}.Builder> internal__{2}__FieldAccessorTable;",
access, FullClassName, identifier);
}
// Generate static members for all nested types.
foreach (MessageDescriptor nestedMessage in Descriptor.NestedTypes) {
new MessageGenerator(nestedMessage).GenerateStaticVariables(writer);
@ -84,21 +86,23 @@ namespace Google.ProtocolBuffers.ProtoGen {
internal void GenerateStaticVariableInitializers(TextGenerator writer) {
string identifier = GetUniqueFileScopeIdentifier(Descriptor);
writer.Write("internal__{0}__Descriptor = ", identifier);
if (Descriptor.ContainingType == null) {
writer.WriteLine("Descriptor.MessageTypes[{0}];", Descriptor.Index);
} else {
writer.WriteLine("internal__{0}__Descriptor.NestedTypes[{1}];", GetUniqueFileScopeIdentifier(Descriptor.ContainingType), Descriptor.Index);
}
if (!UseLiteRuntime) {
writer.Write("internal__{0}__Descriptor = ", identifier);
if (Descriptor.ContainingType == null) {
writer.WriteLine("Descriptor.MessageTypes[{0}];", Descriptor.Index);
} else {
writer.WriteLine("internal__{0}__Descriptor.NestedTypes[{1}];", GetUniqueFileScopeIdentifier(Descriptor.ContainingType), Descriptor.Index);
}
writer.WriteLine("internal__{0}__FieldAccessorTable = ", identifier);
writer.WriteLine(" new pb::FieldAccess.FieldAccessorTable<{1}, {1}.Builder>(internal__{0}__Descriptor,",
identifier, FullClassName);
writer.Print(" new string[] { ");
foreach (FieldDescriptor field in Descriptor.Fields) {
writer.Write("\"{0}\", ", field.CSharpOptions.PropertyName);
writer.WriteLine("internal__{0}__FieldAccessorTable = ", identifier);
writer.WriteLine(" new pb::FieldAccess.FieldAccessorTable<{1}, {1}.Builder>(internal__{0}__Descriptor,",
identifier, FullClassName);
writer.Print(" new string[] { ");
foreach (FieldDescriptor field in Descriptor.Fields) {
writer.Write("\"{0}\", ", field.CSharpOptions.PropertyName);
}
writer.WriteLine("});");
}
writer.WriteLine("});");
// Generate static member initializers for all nested types.
foreach (MessageDescriptor nestedMessage in Descriptor.NestedTypes) {
@ -111,8 +115,10 @@ namespace Google.ProtocolBuffers.ProtoGen {
}
public void Generate(TextGenerator writer) {
writer.WriteLine("{0} sealed partial class {1} : pb::{2}Message<{1}, {1}.Builder> {{",
ClassAccessLevel, ClassName, Descriptor.Proto.ExtensionRangeCount > 0 ? "Extendable" : "Generated");
writer.WriteLine("{0} sealed partial class {1} : pb::{2}Message{3}<{1}, {1}.Builder> {{",
ClassAccessLevel, ClassName,
Descriptor.Proto.ExtensionRangeCount > 0 ? "Extendable" : "Generated",
RuntimeSuffix);
writer.Indent();
// Must call BuildPartial() to make sure all lists are made read-only
writer.WriteLine("private static readonly {0} defaultInstance = new Builder().BuildPartial();", ClassName);
@ -128,16 +134,18 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine(" get { return this; }");
writer.WriteLine("}");
writer.WriteLine();
writer.WriteLine("public static pbd::MessageDescriptor Descriptor {");
writer.WriteLine(" get {{ return {0}.internal__{1}__Descriptor; }}", DescriptorUtil.GetFullUmbrellaClassName(Descriptor),
GetUniqueFileScopeIdentifier(Descriptor));
writer.WriteLine("}");
writer.WriteLine();
writer.WriteLine("protected override pb::FieldAccess.FieldAccessorTable<{0}, {0}.Builder> InternalFieldAccessors {{", ClassName);
writer.WriteLine(" get {{ return {0}.internal__{1}__FieldAccessorTable; }}", DescriptorUtil.GetFullUmbrellaClassName(Descriptor),
GetUniqueFileScopeIdentifier(Descriptor));
writer.WriteLine("}");
writer.WriteLine();
if (!UseLiteRuntime) {
writer.WriteLine("public static pbd::MessageDescriptor Descriptor {");
writer.WriteLine(" get {{ return {0}.internal__{1}__Descriptor; }}", DescriptorUtil.GetFullUmbrellaClassName(Descriptor),
GetUniqueFileScopeIdentifier(Descriptor));
writer.WriteLine("}");
writer.WriteLine();
writer.WriteLine("protected override pb::FieldAccess.FieldAccessorTable<{0}, {0}.Builder> InternalFieldAccessors {{", ClassName);
writer.WriteLine(" get {{ return {0}.internal__{1}__FieldAccessorTable; }}", DescriptorUtil.GetFullUmbrellaClassName(Descriptor),
GetUniqueFileScopeIdentifier(Descriptor));
writer.WriteLine("}");
writer.WriteLine();
}
// Extensions don't need to go in an extra nested type
WriteChildren(writer, null, Descriptor.Extensions);
@ -161,10 +169,13 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine();
}
if (Descriptor.File.Options.OptimizeFor == FileOptions.Types.OptimizeMode.SPEED) {
if (OptimizeSpeed) {
GenerateIsInitialized(writer);
GenerateMessageSerializationMethods(writer);
}
if (UseLiteRuntime) {
GenerateLiteRuntimeMethods(writer);
}
GenerateParseFromMethods(writer);
GenerateBuilder(writer);
@ -184,6 +195,49 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine();
}
private void GenerateLiteRuntimeMethods(TextGenerator writer) {
bool callbase = Descriptor.Proto.ExtensionRangeCount > 0;
writer.WriteLine("#region Lite runtime methods");
writer.WriteLine("public override int GetHashCode() {");
writer.Indent();
writer.WriteLine("int hash = GetType().GetHashCode();");
foreach (FieldDescriptor fieldDescriptor in Descriptor.Fields) {
SourceGenerators.CreateFieldGenerator(fieldDescriptor).WriteHash(writer);
}
if (callbase) writer.WriteLine("hash ^= base.GetHashCode();");
writer.WriteLine("return hash;");
writer.Outdent();
writer.WriteLine("}");
writer.WriteLine();
writer.WriteLine("public override bool Equals(object obj) {");
writer.Indent();
writer.WriteLine("{0} other = obj as {0};", ClassName);
writer.WriteLine("if (other == null) return false;");
foreach (FieldDescriptor fieldDescriptor in Descriptor.Fields) {
SourceGenerators.CreateFieldGenerator(fieldDescriptor).WriteEquals(writer);
}
if (callbase) writer.WriteLine("if (!base.Equals(other)) return false;");
writer.WriteLine("return true;");
writer.Outdent();
writer.WriteLine("}");
writer.WriteLine();
writer.WriteLine("public override void PrintTo(global::System.IO.TextWriter writer) {");
writer.Indent();
List<FieldDescriptor> sorted = new List<FieldDescriptor>(Descriptor.Fields);
sorted.Sort(new Comparison<FieldDescriptor>(delegate(FieldDescriptor a, FieldDescriptor b) { return a.FieldNumber.CompareTo(b.FieldNumber); }));
foreach (FieldDescriptor fieldDescriptor in sorted) {
SourceGenerators.CreateFieldGenerator(fieldDescriptor).WriteToString(writer);
}
if (callbase) writer.WriteLine("base.PrintTo(writer);");
writer.Outdent();
writer.WriteLine("}");
writer.WriteLine("#endregion");
writer.WriteLine();
}
private void GenerateMessageSerializationMethods(TextGenerator writer) {
List<FieldDescriptor> sortedFields = new List<FieldDescriptor>(Descriptor.Fields);
sortedFields.Sort((f1, f2) => f1.FieldNumber.CompareTo(f2.FieldNumber));
@ -196,8 +250,8 @@ namespace Google.ProtocolBuffers.ProtoGen {
// Make sure we've computed the serialized length, so that packed fields are generated correctly.
writer.WriteLine("int size = SerializedSize;");
if (Descriptor.Proto.ExtensionRangeList.Count > 0) {
writer.WriteLine("pb::ExtendableMessage<{0}, {0}.Builder>.ExtensionWriter extensionWriter = CreateExtensionWriter(this);",
ClassName);
writer.WriteLine("pb::ExtendableMessage{1}<{0}, {0}.Builder>.ExtensionWriter extensionWriter = CreateExtensionWriter(this);",
ClassName, RuntimeSuffix);
}
// Merge the fields and the extension ranges, both sorted by field number.
@ -213,10 +267,12 @@ namespace Google.ProtocolBuffers.ProtoGen {
}
}
if (Descriptor.Proto.Options.MessageSetWireFormat) {
writer.WriteLine("UnknownFields.WriteAsMessageSetTo(output);");
} else {
writer.WriteLine("UnknownFields.WriteTo(output);");
if (!UseLiteRuntime) {
if (Descriptor.Proto.Options.MessageSetWireFormat) {
writer.WriteLine("UnknownFields.WriteAsMessageSetTo(output);");
} else {
writer.WriteLine("UnknownFields.WriteTo(output);");
}
}
writer.Outdent();
@ -238,10 +294,12 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine("size += ExtensionsSerializedSize;");
}
if (Descriptor.Options.MessageSetWireFormat) {
writer.WriteLine("size += UnknownFields.SerializedSizeAsMessageSet;");
} else {
writer.WriteLine("size += UnknownFields.SerializedSize;");
if (!UseLiteRuntime) {
if (Descriptor.Options.MessageSetWireFormat) {
writer.WriteLine("size += UnknownFields.SerializedSizeAsMessageSet;");
} else {
writer.WriteLine("size += UnknownFields.SerializedSize;");
}
}
writer.WriteLine("memoizedSerializedSize = size;");
writer.WriteLine("return size;");
@ -345,14 +403,14 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine(" return (Builder) new Builder().MergeFrom(prototype);");
writer.WriteLine("}");
writer.WriteLine();
writer.WriteLine("{0} sealed partial class Builder : pb::{2}Builder<{1}, Builder> {{",
ClassAccessLevel, ClassName, Descriptor.Proto.ExtensionRangeCount > 0 ? "Extendable" : "Generated");
writer.WriteLine("{0} sealed partial class Builder : pb::{2}Builder{3}<{1}, Builder> {{",
ClassAccessLevel, ClassName, Descriptor.Proto.ExtensionRangeCount > 0 ? "Extendable" : "Generated", RuntimeSuffix);
writer.Indent();
writer.WriteLine("protected override Builder ThisBuilder {");
writer.WriteLine(" get { return this; }");
writer.WriteLine("}");
GenerateCommonBuilderMethods(writer);
if (Descriptor.File.Options.OptimizeFor == FileOptions.Types.OptimizeMode.SPEED) {
if (OptimizeSpeed) {
GenerateBuilderParsingMethods(writer);
}
foreach (FieldDescriptor field in Descriptor.Fields) {
@ -382,10 +440,12 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine(" return new Builder().MergeFrom(result);");
writer.WriteLine("}");
writer.WriteLine();
writer.WriteLine("public override pbd::MessageDescriptor DescriptorForType {");
writer.WriteLine(" get {{ return {0}.Descriptor; }}", FullClassName);
writer.WriteLine("}");
writer.WriteLine();
if (!UseLiteRuntime) {
writer.WriteLine("public override pbd::MessageDescriptor DescriptorForType {");
writer.WriteLine(" get {{ return {0}.Descriptor; }}", FullClassName);
writer.WriteLine("}");
writer.WriteLine();
}
writer.WriteLine("public override {0} DefaultInstanceForType {{", ClassName);
writer.WriteLine(" get {{ return {0}.DefaultInstance; }}", FullClassName);
writer.WriteLine("}");
@ -406,8 +466,8 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine("}");
writer.WriteLine();
if (Descriptor.File.Options.OptimizeFor == FileOptions.Types.OptimizeMode.SPEED) {
writer.WriteLine("public override Builder MergeFrom(pb::IMessage other) {");
if (OptimizeSpeed) {
writer.WriteLine("public override Builder MergeFrom(pb::IMessage{0} other) {{", RuntimeSuffix);
writer.WriteLine(" if (other is {0}) {{", ClassName);
writer.WriteLine(" return MergeFrom(({0}) other);", ClassName);
writer.WriteLine(" } else {");
@ -428,7 +488,9 @@ namespace Google.ProtocolBuffers.ProtoGen {
if (Descriptor.Proto.ExtensionRangeCount > 0) {
writer.WriteLine(" this.MergeExtensionFields(other);");
}
writer.WriteLine("this.MergeUnknownFields(other.UnknownFields);");
if (!UseLiteRuntime) {
writer.WriteLine("this.MergeUnknownFields(other.UnknownFields);");
}
writer.WriteLine("return this;");
writer.Outdent();
writer.WriteLine("}");
@ -446,29 +508,37 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine();
writer.WriteLine("public override Builder MergeFrom(pb::CodedInputStream input, pb::ExtensionRegistry extensionRegistry) {");
writer.Indent();
writer.WriteLine("pb::UnknownFieldSet.Builder unknownFields = null;");
if (!UseLiteRuntime) {
writer.WriteLine("pb::UnknownFieldSet.Builder unknownFields = null;");
}
writer.WriteLine("while (true) {");
writer.Indent();
writer.WriteLine("uint tag = input.ReadTag();");
writer.WriteLine("switch (tag) {");
writer.Indent();
writer.WriteLine("case 0: {"); // 0 signals EOF / limit reached
writer.WriteLine(" if (unknownFields != null) {");
writer.WriteLine(" this.UnknownFields = unknownFields.Build();");
writer.WriteLine(" }");
if (!UseLiteRuntime) {
writer.WriteLine(" if (unknownFields != null) {");
writer.WriteLine(" this.UnknownFields = unknownFields.Build();");
writer.WriteLine(" }");
}
writer.WriteLine(" return this;");
writer.WriteLine("}");
writer.WriteLine("default: {");
writer.WriteLine(" if (pb::WireFormat.IsEndGroupTag(tag)) {");
writer.WriteLine(" if (unknownFields != null) {");
writer.WriteLine(" this.UnknownFields = unknownFields.Build();");
writer.WriteLine(" }");
if (!UseLiteRuntime) {
writer.WriteLine(" if (unknownFields != null) {");
writer.WriteLine(" this.UnknownFields = unknownFields.Build();");
writer.WriteLine(" }");
}
writer.WriteLine(" return this;"); // it's an endgroup tag
writer.WriteLine(" }");
writer.WriteLine(" if (unknownFields == null) {"); // First unknown field - create builder now
writer.WriteLine(" unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);");
writer.WriteLine(" }");
writer.WriteLine(" ParseUnknownField(input, unknownFields, extensionRegistry, tag);");
if (!UseLiteRuntime) {
writer.WriteLine(" if (unknownFields == null) {"); // First unknown field - create builder now
writer.WriteLine(" unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);");
writer.WriteLine(" }");
}
writer.WriteLine(" ParseUnknownField(input, {0}extensionRegistry, tag);", UseLiteRuntime ? "" : "unknownFields, ");
writer.WriteLine(" break;");
writer.WriteLine("}");
foreach (FieldDescriptor field in sortedFields) {

@ -103,5 +103,17 @@ namespace Google.ProtocolBuffers.ProtoGen {
CapitalizedTypeName, Number, PropertyName);
writer.WriteLine("}");
}
public override void WriteHash(TextGenerator writer) {
writer.WriteLine("if (has{0}) hash ^= {1}_.GetHashCode();", PropertyName, Name);
}
public override void WriteEquals(TextGenerator writer) {
writer.WriteLine("if (has{0} != other.has{0} || (has{0} && !{1}_.Equals(other.{1}_))) return false;", PropertyName, Name);
}
public override void WriteToString(TextGenerator writer) {
writer.WriteLine("PrintField(\"{0}\", has{1}, {2}_, writer);", Descriptor.Name, PropertyName, Name);
}
}
}

@ -43,7 +43,7 @@ namespace Google.ProtocolBuffers.ProtoGen {
}
public void GenerateMembers(TextGenerator writer) {
if (Descriptor.IsPacked && Descriptor.File.Options.OptimizeFor == FileOptions.Types.OptimizeMode.SPEED) {
if (Descriptor.IsPacked && OptimizeSpeed) {
writer.WriteLine("private int {0}MemoizedSerializedSize;", Name);
}
writer.WriteLine("private pbc::PopsicleList<{0}> {1}_ = new pbc::PopsicleList<{0}>();", TypeName, Name);
@ -114,10 +114,12 @@ namespace Google.ProtocolBuffers.ProtoGen {
// TODO(jonskeet): Make a more efficient way of doing this
writer.WriteLine("int rawValue = input.ReadEnum();");
writer.WriteLine("if (!global::System.Enum.IsDefined(typeof({0}), rawValue)) {{", TypeName);
writer.WriteLine(" if (unknownFields == null) {"); // First unknown field - create builder now
writer.WriteLine(" unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);");
writer.WriteLine(" }");
writer.WriteLine(" unknownFields.MergeVarintField({0}, (ulong) rawValue);", Number);
if (!UseLiteRuntime) {
writer.WriteLine(" if (unknownFields == null) {"); // First unknown field - create builder now
writer.WriteLine(" unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);");
writer.WriteLine(" }");
writer.WriteLine(" unknownFields.MergeVarintField({0}, (ulong) rawValue);", Number);
}
writer.WriteLine("} else {");
writer.WriteLine(" Add{0}(({1}) rawValue);", PropertyName, TypeName);
writer.WriteLine("}");
@ -173,5 +175,20 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.Outdent();
writer.WriteLine("}");
}
public override void WriteHash(TextGenerator writer) {
writer.WriteLine("foreach({0} i in {1}_)", TypeName, Name);
writer.WriteLine(" hash ^= i.GetHashCode();");
}
public override void WriteEquals(TextGenerator writer) {
writer.WriteLine("if({0}_.Count != other.{0}_.Count) return false;", Name);
writer.WriteLine("for(int ix=0; ix < {0}_.Count; ix++)", Name);
writer.WriteLine(" if(!{0}_[ix].Equals(other.{0}_[ix])) return false;", Name);
}
public override void WriteToString(TextGenerator writer) {
writer.WriteLine("PrintField(\"{0}\", {1}_, writer);", Descriptor.Name, Name);
}
}
}

@ -132,5 +132,22 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine(" size += pb::CodedOutputStream.Compute{0}Size({1}, element);", MessageOrGroup, Number);
writer.WriteLine("}");
}
public override void WriteHash(TextGenerator writer) {
writer.WriteLine("foreach({0} i in {1}_)", TypeName, Name);
writer.WriteLine(" hash ^= i.GetHashCode();");
}
public override void WriteEquals(TextGenerator writer) {
writer.WriteLine("if({0}_.Count != other.{0}_.Count) return false;", Name);
writer.WriteLine("for(int ix=0; ix < {0}_.Count; ix++)", Name);
writer.WriteLine(" if(!{0}_[ix].Equals(other.{0}_[ix])) return false;", Name);
}
public override void WriteToString(TextGenerator writer) {
writer.WriteLine("PrintField(\"{0}\", {1}_, writer);",
Descriptor.FieldType == FieldType.Group ? Descriptor.MessageType.Name : Descriptor.Name, Name);
}
}
}

@ -43,7 +43,7 @@ namespace Google.ProtocolBuffers.ProtoGen {
}
public void GenerateMembers(TextGenerator writer) {
if (Descriptor.IsPacked && Descriptor.File.Options.OptimizeFor == FileOptions.Types.OptimizeMode.SPEED) {
if (Descriptor.IsPacked && OptimizeSpeed) {
writer.WriteLine("private int {0}MemoizedSerializedSize;", Name);
}
writer.WriteLine("private pbc::PopsicleList<{0}> {1}_ = new pbc::PopsicleList<{0}>();", TypeName, Name);
@ -168,5 +168,20 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.Outdent();
writer.WriteLine("}");
}
public override void WriteHash(TextGenerator writer) {
writer.WriteLine("foreach({0} i in {1}_)", TypeName, Name);
writer.WriteLine(" hash ^= i.GetHashCode();");
}
public override void WriteEquals(TextGenerator writer) {
writer.WriteLine("if({0}_.Count != other.{0}_.Count) return false;", Name);
writer.WriteLine("for(int ix=0; ix < {0}_.Count; ix++)", Name);
writer.WriteLine(" if(!{0}_[ix].Equals(other.{0}_[ix])) return false;", Name);
}
public override void WriteToString(TextGenerator writer) {
writer.WriteLine("PrintField(\"{0}\", {1}_, writer);", Descriptor.Name, Name);
}
}
}

@ -40,8 +40,20 @@ namespace Google.ProtocolBuffers.ProtoGen {
private readonly T descriptor;
protected readonly bool OptimizeSpeed;
protected readonly bool OptimizeSize;
protected readonly bool UseLiteRuntime;
protected readonly string RuntimeSuffix;
protected SourceGeneratorBase(T descriptor) {
this.descriptor = descriptor;
OptimizeSize = descriptor.File.Options.OptimizeFor == Google.ProtocolBuffers.DescriptorProtos.FileOptions.Types.OptimizeMode.CODE_SIZE;
OptimizeSpeed = descriptor.File.Options.OptimizeFor == Google.ProtocolBuffers.DescriptorProtos.FileOptions.Types.OptimizeMode.SPEED;
UseLiteRuntime = descriptor.File.Options.OptimizeFor == Google.ProtocolBuffers.DescriptorProtos.FileOptions.Types.OptimizeMode.LITE_RUNTIME;
//Lite runtime uses OptimizeSpeed code branches
OptimizeSpeed |= UseLiteRuntime;
RuntimeSuffix = UseLiteRuntime ? "Lite" : "";
}
protected T Descriptor {

@ -74,10 +74,6 @@ namespace Google.ProtocolBuffers.ProtoGen {
return false;
}
public string UmbrellaClassName {
get { throw new NotImplementedException(); }
}
public void Generate(TextGenerator writer) {
WriteIntroduction(writer);
WriteExtensionRegistration(writer);
@ -87,7 +83,11 @@ namespace Google.ProtocolBuffers.ProtoGen {
new MessageGenerator(message).GenerateStaticVariables(writer);
}
writer.WriteLine("#endregion");
WriteDescriptor(writer);
if (!UseLiteRuntime) {
WriteDescriptor(writer);
} else {
WriteLiteExtensions(writer);
}
// The class declaration either gets closed before or after the children are written.
if (!Descriptor.CSharpOptions.NestClasses) {
writer.Outdent();
@ -113,9 +113,12 @@ namespace Google.ProtocolBuffers.ProtoGen {
}
private void WriteIntroduction(TextGenerator writer) {
writer.WriteLine("// Generated by the protocol buffer compiler. DO NOT EDIT!");
writer.WriteLine("// Generated by {0}. DO NOT EDIT!", this.GetType().Assembly.FullName);
writer.WriteLine();
Helpers.WriteNamespaces(writer);
writer.WriteLine("using pb = global::Google.ProtocolBuffers;");
writer.WriteLine("using pbc = global::Google.ProtocolBuffers.Collections;");
writer.WriteLine("using pbd = global::Google.ProtocolBuffers.Descriptors;");
writer.WriteLine("using scg = global::System.Collections.Generic;");
if (Descriptor.CSharpOptions.Namespace != "") {
writer.WriteLine("namespace {0} {{", Descriptor.CSharpOptions.Namespace);
@ -215,5 +218,24 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine("#endregion");
writer.WriteLine();
}
private void WriteLiteExtensions(TextGenerator writer) {
writer.WriteLine("#region Extensions");
writer.WriteLine("internal static readonly object Descriptor;");
writer.WriteLine("static {0}() {{", Descriptor.CSharpOptions.UmbrellaClassname);
writer.Indent();
writer.WriteLine("Descriptor = null;");
foreach (MessageDescriptor message in Descriptor.MessageTypes) {
new MessageGenerator(message).GenerateStaticVariableInitializers(writer);
}
foreach (FieldDescriptor extension in Descriptor.Extensions) {
new ExtensionGenerator(extension).GenerateStaticVariableInitializers(writer);
}
writer.Outdent();
writer.WriteLine("}");
writer.WriteLine("#endregion");
writer.WriteLine();
}
}
}

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

@ -54,37 +54,37 @@
<WarningLevel>4</WarningLevel>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug_Silverlight2|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug_Silverlight2\</OutputPath>
<DefineConstants>DEBUG;TRACE;SILVERLIGHT2</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoStdLib>true</NoStdLib>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release_Silverlight2|AnyCPU'">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release_Silverlight2\</OutputPath>
<DefineConstants>TRACE;SILVERLIGHT2</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoStdLib>true</NoStdLib>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug_Silverlight2|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug_Silverlight2\</OutputPath>
<DefineConstants>DEBUG;TRACE;SILVERLIGHT2</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoStdLib>true</NoStdLib>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release_Silverlight2|AnyCPU'">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release_Silverlight2\</OutputPath>
<DefineConstants>TRACE;SILVERLIGHT2</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoStdLib>true</NoStdLib>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="nunit.framework, Version=2.2.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\nunit.framework.dll</HintPath>
<HintPath>..\..\lib\NUnit 2.2.8.0\nunit.framework.dll</HintPath>
</Reference>
<Reference Include="Rhino.Mocks, Version=3.5.0.2, Culture=neutral, PublicKeyToken=0b3305902db7183f, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\Rhino.Mocks.dll</HintPath>
</Reference>
<Reference Include="mscorlib" />
<Reference Include="mscorlib" />
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
@ -99,6 +99,7 @@
<Compile Include="DescriptorsTest.cs" />
<Compile Include="Descriptors\MessageDescriptorTest.cs" />
<Compile Include="DynamicMessageTest.cs" />
<Compile Include="ExtendableMessageTest.cs" />
<Compile Include="GeneratedMessageTest.cs" />
<Compile Include="MessageStreamIteratorTest.cs" />
<Compile Include="MessageStreamWriterTest.cs" />
@ -111,8 +112,11 @@
<Compile Include="TestProtos\UnitTestCSharpOptionsProtoFile.cs" />
<Compile Include="TestProtos\UnitTestCustomOptionsProtoFile.cs" />
<Compile Include="TestProtos\UnitTestEmbedOptimizeForProtoFile.cs" />
<Compile Include="TestProtos\UnitTestEmptyProtoFile.cs" />
<Compile Include="TestProtos\UnitTestImportLiteProtoFile.cs" />
<Compile Include="TestProtos\UnitTestImportProtoFile.cs" />
<Compile Include="TestProtos\UnitTestMessageSetProtoFile.cs" />
<Compile Include="TestProtos\UnitTestNoGenericServicesProtoFile.cs" />
<Compile Include="TestProtos\UnitTestOptimizeForProtoFile.cs" />
<Compile Include="TestProtos\UnitTestProtoFile.cs" />
<Compile Include="TestUtil.cs" />

@ -213,7 +213,7 @@ namespace Google.ProtocolBuffers {
ExtensionInfo extension = extensionRegistry[field.ContainingType, field.FieldNumber];
Assert.IsNotNull(extension);
Assert.IsNotNull(extension.DefaultInstance);
return extension.DefaultInstance.WeakCreateBuilderForType();
return (IBuilder)extension.DefaultInstance.WeakCreateBuilderForType();
}
}

@ -1,4 +1,4 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// Generated by ProtoGen, Version=0.9.0.0, Culture=neutral, PublicKeyToken=8fd7408b07f8d2cd. DO NOT EDIT!
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;

@ -1,4 +1,4 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// Generated by ProtoGen, Version=0.9.0.0, Culture=neutral, PublicKeyToken=8fd7408b07f8d2cd. DO NOT EDIT!
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;
@ -15,6 +15,7 @@ namespace Google.ProtocolBuffers.TestProtos {
registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.FieldOpt1);
registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.FieldOpt2);
registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.EnumOpt1);
registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.EnumValueOpt1);
registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.ServiceOpt1);
registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.MethodOpt1);
registry.Add(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.BoolOpt);
@ -58,6 +59,8 @@ namespace Google.ProtocolBuffers.TestProtos {
public static pb::GeneratedExtensionBase<int> FieldOpt2;
public const int EnumOpt1FieldNumber = 7753576;
public static pb::GeneratedExtensionBase<int> EnumOpt1;
public const int EnumValueOpt1FieldNumber = 1560678;
public static pb::GeneratedExtensionBase<int> EnumValueOpt1;
public const int ServiceOpt1FieldNumber = 7887650;
public static pb::GeneratedExtensionBase<long> ServiceOpt1;
public const int MethodOpt1FieldNumber = 7890860;
@ -165,97 +168,99 @@ namespace Google.ProtocolBuffers.TestProtos {
"Ci1nb29nbGUvcHJvdG9idWYvdW5pdHRlc3RfY3VzdG9tX29wdGlvbnMucHJv" +
"dG8SEXByb3RvYnVmX3VuaXR0ZXN0GiRnb29nbGUvcHJvdG9idWYvY3NoYXJw" +
"X29wdGlvbnMucHJvdG8aIGdvb2dsZS9wcm90b2J1Zi9kZXNjcmlwdG9yLnBy" +
"b3RvIoYBChxUZXN0TWVzc2FnZVdpdGhDdXN0b21PcHRpb25zEh4KBmZpZWxk" +
"MRgBIAEoCUIOCAHB4MMdLeF1CgIAAAAiNAoGQW5FbnVtEg8KC0FORU5VTV9W" +
"QUwxEAESDwoLQU5FTlVNX1ZBTDIQAhoIxfbJHev8//86EAgA4OnCHcj/////" +
"/////wEiGAoWQ3VzdG9tT3B0aW9uRm9vUmVxdWVzdCIZChdDdXN0b21PcHRp" +
"b25Gb29SZXNwb25zZSJtChpEdW1teU1lc3NhZ2VDb250YWluaW5nRW51bSJP" +
"CgxUZXN0RW51bVR5cGUSGgoWVEVTVF9PUFRJT05fRU5VTV9UWVBFMRAWEiMK" +
"FlRFU1RfT1BUSU9OX0VOVU1fVFlQRTIQ6f//////////ASIhCh9EdW1teU1l" +
"c3NhZ2VJbnZhbGlkQXNPcHRpb25UeXBlIooBChxDdXN0b21PcHRpb25NaW5J" +
"bnRlZ2VyVmFsdWVzOmqZ1qgdAAAAAAAAAICtja8dAAAAgJHurx0AAAAAAAAA" +
"AJ31rx0AAAAA+JewHf///////////wGAxLAd/////w/49bAdAICTsh0AsLyy" +
"HYCAgICAgICAgAHoxrIdgICAgPj/////AdDesh0AIpEBChxDdXN0b21PcHRp" +
"b25NYXhJbnRlZ2VyVmFsdWVzOnGZ1qgd/////////3+tja8d////f5Hurx3/" +
"/////////531rx3/////+JewHf7//////////wGAxLAd/v///w/49bAd////" +
"////////AYCTsh3/////D7C8sh3//////////3/oxrId/////wfQ3rIdASJu" +
"ChdDdXN0b21PcHRpb25PdGhlclZhbHVlczpTiNmiHen//////////wGy2aId" +
"C0hlbGxvAFdvcmxkqtyiHQ5IZWxsbywgIldvcmxkIuncoh37WYxCysDzP/Xf" +
"ox3nh0VB6MayHZz//////////wEiNAocU2V0dGluZ1JlYWxzRnJvbVBvc2l0" +
"aXZlSW50czoU6dyiHQAAAAAAQGNA9d+jHQAAQEEiNAocU2V0dGluZ1JlYWxz" +
"RnJvbU5lZ2F0aXZlSW50czoU6dyiHQAAAAAAQGPA9d+jHQAAQMEiKwoSQ29t" +
"cGxleE9wdGlvblR5cGUxEgsKA2ZvbxgBIAEoBSoICGQQgICAgAIiwQIKEkNv" +
"bXBsZXhPcHRpb25UeXBlMhIyCgNiYXIYASABKAsyJS5wcm90b2J1Zl91bml0" +
"dGVzdC5Db21wbGV4T3B0aW9uVHlwZTESCwoDYmF6GAIgASgFEkYKBGZyZWQY" +
"AyABKAsyOC5wcm90b2J1Zl91bml0dGVzdC5Db21wbGV4T3B0aW9uVHlwZTIu" +
"Q29tcGxleE9wdGlvblR5cGU0GpcBChJDb21wbGV4T3B0aW9uVHlwZTQSDQoF" +
"d2FsZG8YASABKAUycgoMY29tcGxleF9vcHQ0Eh8uZ29vZ2xlLnByb3RvYnVm" +
"Lk1lc3NhZ2VPcHRpb25zGIr10QMgASgLMjgucHJvdG9idWZfdW5pdHRlc3Qu" +
"Q29tcGxleE9wdGlvblR5cGUyLkNvbXBsZXhPcHRpb25UeXBlNCoICGQQgICA" +
"gAIinAEKEkNvbXBsZXhPcHRpb25UeXBlMxILCgNxdXgYASABKAUSVAoSY29t" +
"cGxleG9wdGlvbnR5cGU1GAIgASgKMjgucHJvdG9idWZfdW5pdHRlc3QuQ29t" +
"cGxleE9wdGlvblR5cGUzLkNvbXBsZXhPcHRpb25UeXBlNRojChJDb21wbGV4" +
"T3B0aW9uVHlwZTUSDQoFcGx1Z2gYAyABKAUiHwoLQ29tcGxleE9wdDYSEAoF" +
"eHl6enkY37/PAyABKAUi0AEKFVZhcmlvdXNDb21wbGV4T3B0aW9uczq2AePc" +
"/Bz4/fscGOTc/BzSqI8dAwizD/rekB0CCAn63pAdBBMYFhSq/ZAdAxDbB6r9" +
"kB0G+OaXHY4Fqv2QHQUKAwjnBar9kB0ICgbYhZ4dzw+q/ZAdCgoIkvWdHQMI" +
"2A+q/ZAdCMKslx0DCOUFqv2QHQvCrJcdBtiFnh3OD6r9kB0NwqyXHQiS9Z0d" +
"AwjJEKr9kB0FGgMIwQKi4pUdAggqouKVHQbYhZ4dxAKi4pUdCJL1nR0DCOwG" +
"KjYKCk1ldGhvZE9wdDESEwoPTUVUSE9ET1BUMV9WQUwxEAESEwoPTUVUSE9E" +
"T1BUMV9WQUwyEAIyjgEKHFRlc3RTZXJ2aWNlV2l0aEN1c3RvbU9wdGlvbnMS" +
"YwoDRm9vEikucHJvdG9idWZfdW5pdHRlc3QuQ3VzdG9tT3B0aW9uRm9vUmVx" +
"dWVzdBoqLnByb3RvYnVmX3VuaXR0ZXN0LkN1c3RvbU9wdGlvbkZvb1Jlc3Bv" +
"bnNlIgXg+oweAhoJkLKLHtPbgMtJOjIKCWZpbGVfb3B0MRIcLmdvb2dsZS5w" +
"cm90b2J1Zi5GaWxlT3B0aW9ucxiOndgDIAEoBDo4CgxtZXNzYWdlX29wdDES" +
"Hy5nb29nbGUucHJvdG9idWYuTWVzc2FnZU9wdGlvbnMYnK3YAyABKAU6NAoK" +
"ZmllbGRfb3B0MRIdLmdvb2dsZS5wcm90b2J1Zi5GaWVsZE9wdGlvbnMYiLzY" +
"AyABKAY6OAoKZmllbGRfb3B0MhIdLmdvb2dsZS5wcm90b2J1Zi5GaWVsZE9w" +
"dGlvbnMYuaHZAyABKAU6AjQyOjIKCWVudW1fb3B0MRIcLmdvb2dsZS5wcm90" +
"b2J1Zi5FbnVtT3B0aW9ucxjontkDIAEoDzo4CgxzZXJ2aWNlX29wdDESHy5n" +
"b29nbGUucHJvdG9idWYuU2VydmljZU9wdGlvbnMYorbhAyABKBI6VQoLbWV0" +
"aG9kX29wdDESHi5nb29nbGUucHJvdG9idWYuTWV0aG9kT3B0aW9ucxisz+ED" +
"IAEoDjIdLnByb3RvYnVmX3VuaXR0ZXN0Lk1ldGhvZE9wdDE6NAoIYm9vbF9v" +
"cHQSHy5nb29nbGUucHJvdG9idWYuTWVzc2FnZU9wdGlvbnMY6qvWAyABKAg6" +
"NQoJaW50MzJfb3B0Eh8uZ29vZ2xlLnByb3RvYnVmLk1lc3NhZ2VPcHRpb25z" +
"GO2o1gMgASgFOjUKCWludDY0X29wdBIfLmdvb2dsZS5wcm90b2J1Zi5NZXNz" +
"YWdlT3B0aW9ucxjGp9YDIAEoAzo2Cgp1aW50MzJfb3B0Eh8uZ29vZ2xlLnBy" +
"b3RvYnVmLk1lc3NhZ2VPcHRpb25zGLCi1gMgASgNOjYKCnVpbnQ2NF9vcHQS" +
"Hy5nb29nbGUucHJvdG9idWYuTWVzc2FnZU9wdGlvbnMY347WAyABKAQ6NgoK" +
"c2ludDMyX29wdBIfLmdvb2dsZS5wcm90b2J1Zi5NZXNzYWdlT3B0aW9ucxjA" +
"iNYDIAEoETo2CgpzaW50NjRfb3B0Eh8uZ29vZ2xlLnByb3RvYnVmLk1lc3Nh" +
"Z2VPcHRpb25zGP+C1gMgASgSOjcKC2ZpeGVkMzJfb3B0Eh8uZ29vZ2xlLnBy" +
"b3RvYnVmLk1lc3NhZ2VPcHRpb25zGNP+1QMgASgHOjcKC2ZpeGVkNjRfb3B0" +
"Eh8uZ29vZ2xlLnByb3RvYnVmLk1lc3NhZ2VPcHRpb25zGOL91QMgASgGOjgK" +
"DHNmaXhlZDMyX29wdBIfLmdvb2dsZS5wcm90b2J1Zi5NZXNzYWdlT3B0aW9u" +
"cxjV8dUDIAEoDzo4CgxzZml4ZWQ2NF9vcHQSHy5nb29nbGUucHJvdG9idWYu" +
"TWVzc2FnZU9wdGlvbnMY44rVAyABKBA6NQoJZmxvYXRfb3B0Eh8uZ29vZ2xl" +
"LnByb3RvYnVmLk1lc3NhZ2VPcHRpb25zGP671AMgASgCOjYKCmRvdWJsZV9v" +
"cHQSHy5nb29nbGUucHJvdG9idWYuTWVzc2FnZU9wdGlvbnMYzavUAyABKAE6" +
"NgoKc3RyaW5nX29wdBIfLmdvb2dsZS5wcm90b2J1Zi5NZXNzYWdlT3B0aW9u" +
"cxjFq9QDIAEoCTo1CglieXRlc19vcHQSHy5nb29nbGUucHJvdG9idWYuTWVz" +
"c2FnZU9wdGlvbnMYlqvUAyABKAw6cAoIZW51bV9vcHQSHy5nb29nbGUucHJv" +
"dG9idWYuTWVzc2FnZU9wdGlvbnMYkavUAyABKA4yOi5wcm90b2J1Zl91bml0" +
"dGVzdC5EdW1teU1lc3NhZ2VDb250YWluaW5nRW51bS5UZXN0RW51bVR5cGU6" +
"cAoQbWVzc2FnZV90eXBlX29wdBIfLmdvb2dsZS5wcm90b2J1Zi5NZXNzYWdl" +
"T3B0aW9ucxiv8tMDIAEoCzIyLnByb3RvYnVmX3VuaXR0ZXN0LkR1bW15TWVz" +
"c2FnZUludmFsaWRBc09wdGlvblR5cGU6NgoEcXV1eBIlLnByb3RvYnVmX3Vu" +
"aXR0ZXN0LkNvbXBsZXhPcHRpb25UeXBlMRjb4NMDIAEoBTpeCgVjb3JnZRIl" +
"LnByb3RvYnVmX3VuaXR0ZXN0LkNvbXBsZXhPcHRpb25UeXBlMRjS3tMDIAEo" +
"CzIlLnByb3RvYnVmX3VuaXR0ZXN0LkNvbXBsZXhPcHRpb25UeXBlMzo4CgZn" +
"cmF1bHQSJS5wcm90b2J1Zl91bml0dGVzdC5Db21wbGV4T3B0aW9uVHlwZTIY" +
"7/zSAyABKAU6XwoGZ2FycGx5EiUucHJvdG9idWZfdW5pdHRlc3QuQ29tcGxl" +
"eE9wdGlvblR5cGUyGMj10gMgASgLMiUucHJvdG9idWZfdW5pdHRlc3QuQ29t" +
"cGxleE9wdGlvblR5cGUxOl8KDGNvbXBsZXhfb3B0MRIfLmdvb2dsZS5wcm90" +
"b2J1Zi5NZXNzYWdlT3B0aW9ucxik3NIDIAEoCzIlLnByb3RvYnVmX3VuaXR0" +
"ZXN0LkNvbXBsZXhPcHRpb25UeXBlMTpfCgxjb21wbGV4X29wdDISHy5nb29n" +
"bGUucHJvdG9idWYuTWVzc2FnZU9wdGlvbnMY1Y/SAyABKAsyJS5wcm90b2J1" +
"Zl91bml0dGVzdC5Db21wbGV4T3B0aW9uVHlwZTI6XwoMY29tcGxleF9vcHQz" +
"Eh8uZ29vZ2xlLnByb3RvYnVmLk1lc3NhZ2VPcHRpb25zGO+L0gMgASgLMiUu" +
"cHJvdG9idWZfdW5pdHRlc3QuQ29tcGxleE9wdGlvblR5cGUzOlcKC2NvbXBs" +
"ZXhvcHQ2Eh8uZ29vZ2xlLnByb3RvYnVmLk1lc3NhZ2VPcHRpb25zGMzLzwMg" +
"ASgKMh4ucHJvdG9idWZfdW5pdHRlc3QuQ29tcGxleE9wdDZCT8I+QwohR29v" +
"Z2xlLlByb3RvY29sQnVmZmVycy5UZXN0UHJvdG9zEh5Vbml0VGVzdEN1c3Rv" +
"bU9wdGlvbnNQcm90b0ZpbGXw6MEd6q3A5SQ=");
"b3RvIo0BChxUZXN0TWVzc2FnZVdpdGhDdXN0b21PcHRpb25zEh4KBmZpZWxk" +
"MRgBIAEoCUIOCAHB4MMdLeF1CgIAAAAiOwoGQW5FbnVtEg8KC0FORU5VTV9W" +
"QUwxEAESFgoLQU5FTlVNX1ZBTDIQAhoFsIb6BXsaCMX2yR3r/P//OhAIAODp" +
"wh3I//////////8BIhgKFkN1c3RvbU9wdGlvbkZvb1JlcXVlc3QiGQoXQ3Vz" +
"dG9tT3B0aW9uRm9vUmVzcG9uc2UibQoaRHVtbXlNZXNzYWdlQ29udGFpbmlu" +
"Z0VudW0iTwoMVGVzdEVudW1UeXBlEhoKFlRFU1RfT1BUSU9OX0VOVU1fVFlQ" +
"RTEQFhIjChZURVNUX09QVElPTl9FTlVNX1RZUEUyEOn//////////wEiIQof" +
"RHVtbXlNZXNzYWdlSW52YWxpZEFzT3B0aW9uVHlwZSKKAQocQ3VzdG9tT3B0" +
"aW9uTWluSW50ZWdlclZhbHVlczpqmdaoHQAAAAAAAACArY2vHQAAAICR7q8d" +
"AAAAAAAAAACd9a8dAAAAAPiXsB3///////////8BgMSwHf////8P+PWwHQCA" +
"k7IdALC8sh2AgICAgICAgIAB6MayHYCAgID4/////wHQ3rIdACKRAQocQ3Vz" +
"dG9tT3B0aW9uTWF4SW50ZWdlclZhbHVlczpxmdaoHf////////9/rY2vHf//" +
"/3+R7q8d//////////+d9a8d//////iXsB3+//////////8BgMSwHf7///8P" +
"+PWwHf///////////wGAk7Id/////w+wvLId//////////9/6MayHf////8H" +
"0N6yHQEibgoXQ3VzdG9tT3B0aW9uT3RoZXJWYWx1ZXM6U4jZoh3p////////" +
"//8BstmiHQtIZWxsbwBXb3JsZKrcoh0OSGVsbG8sICJXb3JsZCLp3KId+1mM" +
"QsrA8z/136Md54dFQejGsh2c//////////8BIjQKHFNldHRpbmdSZWFsc0Zy" +
"b21Qb3NpdGl2ZUludHM6FOncoh0AAAAAAEBjQPXfox0AAEBBIjQKHFNldHRp" +
"bmdSZWFsc0Zyb21OZWdhdGl2ZUludHM6FOncoh0AAAAAAEBjwPXfox0AAEDB" +
"IkcKEkNvbXBsZXhPcHRpb25UeXBlMRILCgNmb28YASABKAUSDAoEZm9vMhgC" +
"IAEoBRIMCgRmb28zGAMgASgFKggIZBCAgICAAiLBAgoSQ29tcGxleE9wdGlv" +
"blR5cGUyEjIKA2JhchgBIAEoCzIlLnByb3RvYnVmX3VuaXR0ZXN0LkNvbXBs" +
"ZXhPcHRpb25UeXBlMRILCgNiYXoYAiABKAUSRgoEZnJlZBgDIAEoCzI4LnBy" +
"b3RvYnVmX3VuaXR0ZXN0LkNvbXBsZXhPcHRpb25UeXBlMi5Db21wbGV4T3B0" +
"aW9uVHlwZTQalwEKEkNvbXBsZXhPcHRpb25UeXBlNBINCgV3YWxkbxgBIAEo" +
"BTJyCgxjb21wbGV4X29wdDQSHy5nb29nbGUucHJvdG9idWYuTWVzc2FnZU9w" +
"dGlvbnMYivXRAyABKAsyOC5wcm90b2J1Zl91bml0dGVzdC5Db21wbGV4T3B0" +
"aW9uVHlwZTIuQ29tcGxleE9wdGlvblR5cGU0KggIZBCAgICAAiKcAQoSQ29t" +
"cGxleE9wdGlvblR5cGUzEgsKA3F1eBgBIAEoBRJUChJjb21wbGV4b3B0aW9u" +
"dHlwZTUYAiABKAoyOC5wcm90b2J1Zl91bml0dGVzdC5Db21wbGV4T3B0aW9u" +
"VHlwZTMuQ29tcGxleE9wdGlvblR5cGU1GiMKEkNvbXBsZXhPcHRpb25UeXBl" +
"NRINCgVwbHVnaBgDIAEoBSIfCgtDb21wbGV4T3B0NhIQCgV4eXp6eRjfv88D" +
"IAEoBSLQAQoVVmFyaW91c0NvbXBsZXhPcHRpb25zOrYB49z8HPj9+xwY5Nz8" +
"HNKojx0DCLMP+t6QHQIICfrekB0EExgWFKr9kB0DENsHqv2QHQb45pcdjgWq" +
"/ZAdBQoDCOcFqv2QHQgKBtiFnh3PD6r9kB0KCgiS9Z0dAwjYD6r9kB0IwqyX" +
"HQMI5QWq/ZAdC8Kslx0G2IWeHc4Pqv2QHQ3CrJcdCJL1nR0DCMkQqv2QHQUa" +
"AwjBAqLilR0CCCqi4pUdBtiFnh3EAqLilR0IkvWdHQMI7AYqNgoKTWV0aG9k" +
"T3B0MRITCg9NRVRIT0RPUFQxX1ZBTDEQARITCg9NRVRIT0RPUFQxX1ZBTDIQ" +
"AjKOAQocVGVzdFNlcnZpY2VXaXRoQ3VzdG9tT3B0aW9ucxJjCgNGb28SKS5w" +
"cm90b2J1Zl91bml0dGVzdC5DdXN0b21PcHRpb25Gb29SZXF1ZXN0GioucHJv" +
"dG9idWZfdW5pdHRlc3QuQ3VzdG9tT3B0aW9uRm9vUmVzcG9uc2UiBeD6jB4C" +
"GgmQsose09uAy0k6MgoJZmlsZV9vcHQxEhwuZ29vZ2xlLnByb3RvYnVmLkZp" +
"bGVPcHRpb25zGI6d2AMgASgEOjgKDG1lc3NhZ2Vfb3B0MRIfLmdvb2dsZS5w" +
"cm90b2J1Zi5NZXNzYWdlT3B0aW9ucxicrdgDIAEoBTo0CgpmaWVsZF9vcHQx" +
"Eh0uZ29vZ2xlLnByb3RvYnVmLkZpZWxkT3B0aW9ucxiIvNgDIAEoBjo4Cgpm" +
"aWVsZF9vcHQyEh0uZ29vZ2xlLnByb3RvYnVmLkZpZWxkT3B0aW9ucxi5odkD" +
"IAEoBToCNDI6MgoJZW51bV9vcHQxEhwuZ29vZ2xlLnByb3RvYnVmLkVudW1P" +
"cHRpb25zGOie2QMgASgPOjwKD2VudW1fdmFsdWVfb3B0MRIhLmdvb2dsZS5w" +
"cm90b2J1Zi5FbnVtVmFsdWVPcHRpb25zGOagXyABKAU6OAoMc2VydmljZV9v" +
"cHQxEh8uZ29vZ2xlLnByb3RvYnVmLlNlcnZpY2VPcHRpb25zGKK24QMgASgS" +
"OlUKC21ldGhvZF9vcHQxEh4uZ29vZ2xlLnByb3RvYnVmLk1ldGhvZE9wdGlv" +
"bnMYrM/hAyABKA4yHS5wcm90b2J1Zl91bml0dGVzdC5NZXRob2RPcHQxOjQK" +
"CGJvb2xfb3B0Eh8uZ29vZ2xlLnByb3RvYnVmLk1lc3NhZ2VPcHRpb25zGOqr" +
"1gMgASgIOjUKCWludDMyX29wdBIfLmdvb2dsZS5wcm90b2J1Zi5NZXNzYWdl" +
"T3B0aW9ucxjtqNYDIAEoBTo1CglpbnQ2NF9vcHQSHy5nb29nbGUucHJvdG9i" +
"dWYuTWVzc2FnZU9wdGlvbnMYxqfWAyABKAM6NgoKdWludDMyX29wdBIfLmdv" +
"b2dsZS5wcm90b2J1Zi5NZXNzYWdlT3B0aW9ucxiwotYDIAEoDTo2Cgp1aW50" +
"NjRfb3B0Eh8uZ29vZ2xlLnByb3RvYnVmLk1lc3NhZ2VPcHRpb25zGN+O1gMg" +
"ASgEOjYKCnNpbnQzMl9vcHQSHy5nb29nbGUucHJvdG9idWYuTWVzc2FnZU9w" +
"dGlvbnMYwIjWAyABKBE6NgoKc2ludDY0X29wdBIfLmdvb2dsZS5wcm90b2J1" +
"Zi5NZXNzYWdlT3B0aW9ucxj/gtYDIAEoEjo3CgtmaXhlZDMyX29wdBIfLmdv" +
"b2dsZS5wcm90b2J1Zi5NZXNzYWdlT3B0aW9ucxjT/tUDIAEoBzo3CgtmaXhl" +
"ZDY0X29wdBIfLmdvb2dsZS5wcm90b2J1Zi5NZXNzYWdlT3B0aW9ucxji/dUD" +
"IAEoBjo4CgxzZml4ZWQzMl9vcHQSHy5nb29nbGUucHJvdG9idWYuTWVzc2Fn" +
"ZU9wdGlvbnMY1fHVAyABKA86OAoMc2ZpeGVkNjRfb3B0Eh8uZ29vZ2xlLnBy" +
"b3RvYnVmLk1lc3NhZ2VPcHRpb25zGOOK1QMgASgQOjUKCWZsb2F0X29wdBIf" +
"Lmdvb2dsZS5wcm90b2J1Zi5NZXNzYWdlT3B0aW9ucxj+u9QDIAEoAjo2Cgpk" +
"b3VibGVfb3B0Eh8uZ29vZ2xlLnByb3RvYnVmLk1lc3NhZ2VPcHRpb25zGM2r" +
"1AMgASgBOjYKCnN0cmluZ19vcHQSHy5nb29nbGUucHJvdG9idWYuTWVzc2Fn" +
"ZU9wdGlvbnMYxavUAyABKAk6NQoJYnl0ZXNfb3B0Eh8uZ29vZ2xlLnByb3Rv" +
"YnVmLk1lc3NhZ2VPcHRpb25zGJar1AMgASgMOnAKCGVudW1fb3B0Eh8uZ29v" +
"Z2xlLnByb3RvYnVmLk1lc3NhZ2VPcHRpb25zGJGr1AMgASgOMjoucHJvdG9i" +
"dWZfdW5pdHRlc3QuRHVtbXlNZXNzYWdlQ29udGFpbmluZ0VudW0uVGVzdEVu" +
"dW1UeXBlOnAKEG1lc3NhZ2VfdHlwZV9vcHQSHy5nb29nbGUucHJvdG9idWYu" +
"TWVzc2FnZU9wdGlvbnMYr/LTAyABKAsyMi5wcm90b2J1Zl91bml0dGVzdC5E" +
"dW1teU1lc3NhZ2VJbnZhbGlkQXNPcHRpb25UeXBlOjYKBHF1dXgSJS5wcm90" +
"b2J1Zl91bml0dGVzdC5Db21wbGV4T3B0aW9uVHlwZTEY2+DTAyABKAU6XgoF" +
"Y29yZ2USJS5wcm90b2J1Zl91bml0dGVzdC5Db21wbGV4T3B0aW9uVHlwZTEY" +
"0t7TAyABKAsyJS5wcm90b2J1Zl91bml0dGVzdC5Db21wbGV4T3B0aW9uVHlw" +
"ZTM6OAoGZ3JhdWx0EiUucHJvdG9idWZfdW5pdHRlc3QuQ29tcGxleE9wdGlv" +
"blR5cGUyGO/80gMgASgFOl8KBmdhcnBseRIlLnByb3RvYnVmX3VuaXR0ZXN0" +
"LkNvbXBsZXhPcHRpb25UeXBlMhjI9dIDIAEoCzIlLnByb3RvYnVmX3VuaXR0" +
"ZXN0LkNvbXBsZXhPcHRpb25UeXBlMTpfCgxjb21wbGV4X29wdDESHy5nb29n" +
"bGUucHJvdG9idWYuTWVzc2FnZU9wdGlvbnMYpNzSAyABKAsyJS5wcm90b2J1" +
"Zl91bml0dGVzdC5Db21wbGV4T3B0aW9uVHlwZTE6XwoMY29tcGxleF9vcHQy" +
"Eh8uZ29vZ2xlLnByb3RvYnVmLk1lc3NhZ2VPcHRpb25zGNWP0gMgASgLMiUu" +
"cHJvdG9idWZfdW5pdHRlc3QuQ29tcGxleE9wdGlvblR5cGUyOl8KDGNvbXBs" +
"ZXhfb3B0MxIfLmdvb2dsZS5wcm90b2J1Zi5NZXNzYWdlT3B0aW9ucxjvi9ID" +
"IAEoCzIlLnByb3RvYnVmX3VuaXR0ZXN0LkNvbXBsZXhPcHRpb25UeXBlMzpX" +
"Cgtjb21wbGV4b3B0NhIfLmdvb2dsZS5wcm90b2J1Zi5NZXNzYWdlT3B0aW9u" +
"cxjMy88DIAEoCjIeLnByb3RvYnVmX3VuaXR0ZXN0LkNvbXBsZXhPcHQ2Qk/C" +
"PkMKIUdvb2dsZS5Qcm90b2NvbEJ1ZmZlcnMuVGVzdFByb3RvcxIeVW5pdFRl" +
"c3RDdXN0b21PcHRpb25zUHJvdG9GaWxl8OjBHeqtwOUk");
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_protobuf_unittest_TestMessageWithCustomOptions__Descriptor = Descriptor.MessageTypes[0];
@ -301,7 +306,7 @@ namespace Google.ProtocolBuffers.TestProtos {
internal__static_protobuf_unittest_ComplexOptionType1__Descriptor = Descriptor.MessageTypes[10];
internal__static_protobuf_unittest_ComplexOptionType1__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.ComplexOptionType1, global::Google.ProtocolBuffers.TestProtos.ComplexOptionType1.Builder>(internal__static_protobuf_unittest_ComplexOptionType1__Descriptor,
new string[] { "Foo", });
new string[] { "Foo", "Foo2", "Foo3", });
internal__static_protobuf_unittest_ComplexOptionType2__Descriptor = Descriptor.MessageTypes[11];
internal__static_protobuf_unittest_ComplexOptionType2__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.ComplexOptionType2, global::Google.ProtocolBuffers.TestProtos.ComplexOptionType2.Builder>(internal__static_protobuf_unittest_ComplexOptionType2__Descriptor,
@ -332,33 +337,34 @@ namespace Google.ProtocolBuffers.TestProtos {
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.FieldOpt1 = pb::GeneratedSingleExtension<ulong>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[2]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.FieldOpt2 = pb::GeneratedSingleExtension<int>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[3]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.EnumOpt1 = pb::GeneratedSingleExtension<int>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[4]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.ServiceOpt1 = pb::GeneratedSingleExtension<long>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[5]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.MethodOpt1 = pb::GeneratedSingleExtension<global::Google.ProtocolBuffers.TestProtos.MethodOpt1>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[6]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.BoolOpt = pb::GeneratedSingleExtension<bool>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[7]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Int32Opt = pb::GeneratedSingleExtension<int>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[8]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Int64Opt = pb::GeneratedSingleExtension<long>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[9]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Uint32Opt = pb::GeneratedSingleExtension<uint>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[10]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Uint64Opt = pb::GeneratedSingleExtension<ulong>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[11]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Sint32Opt = pb::GeneratedSingleExtension<int>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[12]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Sint64Opt = pb::GeneratedSingleExtension<long>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[13]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Fixed32Opt = pb::GeneratedSingleExtension<uint>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[14]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Fixed64Opt = pb::GeneratedSingleExtension<ulong>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[15]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Sfixed32Opt = pb::GeneratedSingleExtension<int>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[16]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Sfixed64Opt = pb::GeneratedSingleExtension<long>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[17]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.FloatOpt = pb::GeneratedSingleExtension<float>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[18]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.DoubleOpt = pb::GeneratedSingleExtension<double>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[19]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.StringOpt = pb::GeneratedSingleExtension<string>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[20]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.BytesOpt = pb::GeneratedSingleExtension<pb::ByteString>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[21]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.EnumOpt = pb::GeneratedSingleExtension<global::Google.ProtocolBuffers.TestProtos.DummyMessageContainingEnum.Types.TestEnumType>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[22]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.MessageTypeOpt = pb::GeneratedSingleExtension<global::Google.ProtocolBuffers.TestProtos.DummyMessageInvalidAsOptionType>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[23]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Quux = pb::GeneratedSingleExtension<int>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[24]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Corge = pb::GeneratedSingleExtension<global::Google.ProtocolBuffers.TestProtos.ComplexOptionType3>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[25]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Grault = pb::GeneratedSingleExtension<int>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[26]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Garply = pb::GeneratedSingleExtension<global::Google.ProtocolBuffers.TestProtos.ComplexOptionType1>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[27]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.ComplexOpt1 = pb::GeneratedSingleExtension<global::Google.ProtocolBuffers.TestProtos.ComplexOptionType1>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[28]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.ComplexOpt2 = pb::GeneratedSingleExtension<global::Google.ProtocolBuffers.TestProtos.ComplexOptionType2>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[29]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.ComplexOpt3 = pb::GeneratedSingleExtension<global::Google.ProtocolBuffers.TestProtos.ComplexOptionType3>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[30]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.ComplexOpt6 = pb::GeneratedSingleExtension<global::Google.ProtocolBuffers.TestProtos.ComplexOpt6>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[31]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.EnumValueOpt1 = pb::GeneratedSingleExtension<int>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[5]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.ServiceOpt1 = pb::GeneratedSingleExtension<long>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[6]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.MethodOpt1 = pb::GeneratedSingleExtension<global::Google.ProtocolBuffers.TestProtos.MethodOpt1>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[7]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.BoolOpt = pb::GeneratedSingleExtension<bool>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[8]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Int32Opt = pb::GeneratedSingleExtension<int>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[9]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Int64Opt = pb::GeneratedSingleExtension<long>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[10]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Uint32Opt = pb::GeneratedSingleExtension<uint>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[11]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Uint64Opt = pb::GeneratedSingleExtension<ulong>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[12]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Sint32Opt = pb::GeneratedSingleExtension<int>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[13]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Sint64Opt = pb::GeneratedSingleExtension<long>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[14]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Fixed32Opt = pb::GeneratedSingleExtension<uint>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[15]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Fixed64Opt = pb::GeneratedSingleExtension<ulong>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[16]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Sfixed32Opt = pb::GeneratedSingleExtension<int>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[17]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Sfixed64Opt = pb::GeneratedSingleExtension<long>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[18]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.FloatOpt = pb::GeneratedSingleExtension<float>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[19]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.DoubleOpt = pb::GeneratedSingleExtension<double>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[20]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.StringOpt = pb::GeneratedSingleExtension<string>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[21]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.BytesOpt = pb::GeneratedSingleExtension<pb::ByteString>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[22]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.EnumOpt = pb::GeneratedSingleExtension<global::Google.ProtocolBuffers.TestProtos.DummyMessageContainingEnum.Types.TestEnumType>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[23]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.MessageTypeOpt = pb::GeneratedSingleExtension<global::Google.ProtocolBuffers.TestProtos.DummyMessageInvalidAsOptionType>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[24]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Quux = pb::GeneratedSingleExtension<int>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[25]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Corge = pb::GeneratedSingleExtension<global::Google.ProtocolBuffers.TestProtos.ComplexOptionType3>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[26]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Grault = pb::GeneratedSingleExtension<int>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[27]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Garply = pb::GeneratedSingleExtension<global::Google.ProtocolBuffers.TestProtos.ComplexOptionType1>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[28]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.ComplexOpt1 = pb::GeneratedSingleExtension<global::Google.ProtocolBuffers.TestProtos.ComplexOptionType1>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[29]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.ComplexOpt2 = pb::GeneratedSingleExtension<global::Google.ProtocolBuffers.TestProtos.ComplexOptionType2>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[30]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.ComplexOpt3 = pb::GeneratedSingleExtension<global::Google.ProtocolBuffers.TestProtos.ComplexOptionType3>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[31]);
global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.ComplexOpt6 = pb::GeneratedSingleExtension<global::Google.ProtocolBuffers.TestProtos.ComplexOpt6>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor.Extensions[32]);
pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance();
RegisterAllExtensions(registry);
global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.RegisterAllExtensions(registry);
@ -2217,6 +2223,26 @@ namespace Google.ProtocolBuffers.TestProtos {
get { return foo_; }
}
public const int Foo2FieldNumber = 2;
private bool hasFoo2;
private int foo2_ = 0;
public bool HasFoo2 {
get { return hasFoo2; }
}
public int Foo2 {
get { return foo2_; }
}
public const int Foo3FieldNumber = 3;
private bool hasFoo3;
private int foo3_ = 0;
public bool HasFoo3 {
get { return hasFoo3; }
}
public int Foo3 {
get { return foo3_; }
}
public override bool IsInitialized {
get {
if (!ExtensionsAreInitialized) return false;
@ -2230,6 +2256,12 @@ namespace Google.ProtocolBuffers.TestProtos {
if (HasFoo) {
output.WriteInt32(1, Foo);
}
if (HasFoo2) {
output.WriteInt32(2, Foo2);
}
if (HasFoo3) {
output.WriteInt32(3, Foo3);
}
extensionWriter.WriteUntil(536870912, output);
UnknownFields.WriteTo(output);
}
@ -2244,6 +2276,12 @@ namespace Google.ProtocolBuffers.TestProtos {
if (HasFoo) {
size += pb::CodedOutputStream.ComputeInt32Size(1, Foo);
}
if (HasFoo2) {
size += pb::CodedOutputStream.ComputeInt32Size(2, Foo2);
}
if (HasFoo3) {
size += pb::CodedOutputStream.ComputeInt32Size(3, Foo3);
}
size += ExtensionsSerializedSize;
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
@ -2339,6 +2377,12 @@ namespace Google.ProtocolBuffers.TestProtos {
if (other == global::Google.ProtocolBuffers.TestProtos.ComplexOptionType1.DefaultInstance) return this;
if (other.HasFoo) {
Foo = other.Foo;
}
if (other.HasFoo2) {
Foo2 = other.Foo2;
}
if (other.HasFoo3) {
Foo3 = other.Foo3;
}
this.MergeExtensionFields(other);
this.MergeUnknownFields(other.UnknownFields);
@ -2377,6 +2421,14 @@ namespace Google.ProtocolBuffers.TestProtos {
Foo = input.ReadInt32();
break;
}
case 16: {
Foo2 = input.ReadInt32();
break;
}
case 24: {
Foo3 = input.ReadInt32();
break;
}
}
}
}
@ -2399,6 +2451,42 @@ namespace Google.ProtocolBuffers.TestProtos {
result.foo_ = 0;
return this;
}
public bool HasFoo2 {
get { return result.HasFoo2; }
}
public int Foo2 {
get { return result.Foo2; }
set { SetFoo2(value); }
}
public Builder SetFoo2(int value) {
result.hasFoo2 = true;
result.foo2_ = value;
return this;
}
public Builder ClearFoo2() {
result.hasFoo2 = false;
result.foo2_ = 0;
return this;
}
public bool HasFoo3 {
get { return result.HasFoo3; }
}
public int Foo3 {
get { return result.Foo3; }
set { SetFoo3(value); }
}
public Builder SetFoo3(int value) {
result.hasFoo3 = true;
result.foo3_ = value;
return this;
}
public Builder ClearFoo3() {
result.hasFoo3 = false;
result.foo3_ = 0;
return this;
}
}
static ComplexOptionType1() {
object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.UnitTestCustomOptionsProtoFile.Descriptor, null);

@ -1,4 +1,4 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// Generated by ProtoGen, Version=0.9.0.0, Culture=neutral, PublicKeyToken=8fd7408b07f8d2cd. DO NOT EDIT!
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;

@ -0,0 +1,44 @@
// Generated by ProtoGen, Version=0.9.0.0, Culture=neutral, PublicKeyToken=8fd7408b07f8d2cd. DO NOT EDIT!
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 {
public static partial class UnitTestEmptyProtoFile {
#region Extension registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
}
#endregion
#region Static variables
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static UnitTestEmptyProtoFile() {
byte[] descriptorData = global::System.Convert.FromBase64String(
"CiRnb29nbGUvcHJvdG9idWYvdW5pdHRlc3RfZW1wdHkucHJvdG8aJGdvb2ds" +
"ZS9wcm90b2J1Zi9jc2hhcnBfb3B0aW9ucy5wcm90b0I+wj47CiFHb29nbGUu" +
"UHJvdG9jb2xCdWZmZXJzLlRlc3RQcm90b3MSFlVuaXRUZXN0RW1wdHlQcm90" +
"b0ZpbGU=");
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance();
RegisterAllExtensions(registry);
global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.RegisterAllExtensions(registry);
return registry;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.Descriptor,
}, assigner);
}
#endregion
}
}

@ -0,0 +1,196 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
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 {
public static partial class UnitTestImportLiteProtoFile {
#region Extension registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
}
#endregion
#region Static variables
internal static pbd::MessageDescriptor internal__static_protobuf_unittest_import_ImportMessageLite__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.ImportMessageLite, global::Google.ProtocolBuffers.TestProtos.ImportMessageLite.Builder> internal__static_protobuf_unittest_import_ImportMessageLite__FieldAccessorTable;
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static UnitTestImportLiteProtoFile() {
byte[] descriptorData = global::System.Convert.FromBase64String(
"Cipnb29nbGUvcHJvdG9idWYvdW5pdHRlc3RfaW1wb3J0X2xpdGUucHJvdG8S" +
"GHByb3RvYnVmX3VuaXR0ZXN0X2ltcG9ydBokZ29vZ2xlL3Byb3RvYnVmL2Nz" +
"aGFycF9vcHRpb25zLnByb3RvIh4KEUltcG9ydE1lc3NhZ2VMaXRlEgkKAWQY" +
"ASABKAUqTwoOSW1wb3J0RW51bUxpdGUSEwoPSU1QT1JUX0xJVEVfRk9PEAcS" +
"EwoPSU1QT1JUX0xJVEVfQkFSEAgSEwoPSU1QT1JUX0xJVEVfQkFaEAlCWgoT" +
"Y29tLmdvb2dsZS5wcm90b2J1ZkgDwj5ACiFHb29nbGUuUHJvdG9jb2xCdWZm" +
"ZXJzLlRlc3RQcm90b3MSG1VuaXRUZXN0SW1wb3J0TGl0ZVByb3RvRmlsZQ==");
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_protobuf_unittest_import_ImportMessageLite__Descriptor = Descriptor.MessageTypes[0];
internal__static_protobuf_unittest_import_ImportMessageLite__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.ImportMessageLite, global::Google.ProtocolBuffers.TestProtos.ImportMessageLite.Builder>(internal__static_protobuf_unittest_import_ImportMessageLite__Descriptor,
new string[] { "D", });
pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance();
RegisterAllExtensions(registry);
global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.RegisterAllExtensions(registry);
return registry;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.Descriptor,
}, assigner);
}
#endregion
}
#region Enums
public enum ImportEnumLite {
IMPORT_LITE_FOO = 7,
IMPORT_LITE_BAR = 8,
IMPORT_LITE_BAZ = 9,
}
#endregion
#region Messages
public sealed partial class ImportMessageLite : pb::GeneratedMessage<ImportMessageLite, ImportMessageLite.Builder> {
private static readonly ImportMessageLite defaultInstance = new Builder().BuildPartial();
public static ImportMessageLite DefaultInstance {
get { return defaultInstance; }
}
public override ImportMessageLite DefaultInstanceForType {
get { return defaultInstance; }
}
protected override ImportMessageLite ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::Google.ProtocolBuffers.TestProtos.UnitTestImportLiteProtoFile.internal__static_protobuf_unittest_import_ImportMessageLite__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<ImportMessageLite, ImportMessageLite.Builder> InternalFieldAccessors {
get { return global::Google.ProtocolBuffers.TestProtos.UnitTestImportLiteProtoFile.internal__static_protobuf_unittest_import_ImportMessageLite__FieldAccessorTable; }
}
public const int DFieldNumber = 1;
private bool hasD;
private int d_ = 0;
public bool HasD {
get { return hasD; }
}
public int D {
get { return d_; }
}
public static ImportMessageLite ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static ImportMessageLite ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static ImportMessageLite ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static ImportMessageLite ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static ImportMessageLite ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static ImportMessageLite ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static ImportMessageLite ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static ImportMessageLite ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static ImportMessageLite ParseFrom(pb::CodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static ImportMessageLite ParseFrom(pb::CodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
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(ImportMessageLite prototype) {
return (Builder) new Builder().MergeFrom(prototype);
}
public sealed partial class Builder : pb::GeneratedBuilder<ImportMessageLite, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {}
ImportMessageLite result = new ImportMessageLite();
protected override ImportMessageLite MessageBeingBuilt {
get { return result; }
}
public override Builder Clear() {
result = new ImportMessageLite();
return this;
}
public override Builder Clone() {
return new Builder().MergeFrom(result);
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::Google.ProtocolBuffers.TestProtos.ImportMessageLite.Descriptor; }
}
public override ImportMessageLite DefaultInstanceForType {
get { return global::Google.ProtocolBuffers.TestProtos.ImportMessageLite.DefaultInstance; }
}
public override ImportMessageLite BuildPartial() {
if (result == null) {
throw new global::System.InvalidOperationException("build() has already been called on this Builder");
}
ImportMessageLite returnMe = result;
result = null;
return returnMe;
}
public bool HasD {
get { return result.HasD; }
}
public int D {
get { return result.D; }
set { SetD(value); }
}
public Builder SetD(int value) {
result.hasD = true;
result.d_ = value;
return this;
}
public Builder ClearD() {
result.hasD = false;
result.d_ = 0;
return this;
}
}
static ImportMessageLite() {
object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.UnitTestImportLiteProtoFile.Descriptor, null);
}
}
#endregion
}

@ -1,4 +1,4 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// Generated by ProtoGen, Version=0.9.0.0, Culture=neutral, PublicKeyToken=8fd7408b07f8d2cd. DO NOT EDIT!
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;

@ -1,4 +1,4 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// Generated by ProtoGen, Version=0.9.0.0, Culture=neutral, PublicKeyToken=8fd7408b07f8d2cd. DO NOT EDIT!
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;

@ -0,0 +1,382 @@
// Generated by ProtoGen, Version=0.9.0.0, Culture=neutral, PublicKeyToken=8fd7408b07f8d2cd. DO NOT EDIT!
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.NoGenericService {
public static partial class UnitTestNoGenericServicesProtoFile {
#region Extension registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
registry.Add(global::Google.ProtocolBuffers.TestProtos.NoGenericService.UnitTestNoGenericServicesProtoFile.TestExtension);
}
#endregion
#region Extensions
public const int TestExtensionFieldNumber = 1000;
public static pb::GeneratedExtensionBase<int> TestExtension;
#endregion
#region Static variables
internal static pbd::MessageDescriptor internal__static_google_protobuf_no_generic_services_test_TestMessage__Descriptor;
internal static pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.NoGenericService.TestMessage, global::Google.ProtocolBuffers.TestProtos.NoGenericService.TestMessage.Builder> internal__static_google_protobuf_no_generic_services_test_TestMessage__FieldAccessorTable;
#endregion
#region Descriptor
public static pbd::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbd::FileDescriptor descriptor;
static UnitTestNoGenericServicesProtoFile() {
byte[] descriptorData = global::System.Convert.FromBase64String(
"CjJnb29nbGUvcHJvdG9idWYvdW5pdHRlc3Rfbm9fZ2VuZXJpY19zZXJ2aWNl" +
"cy5wcm90bxIoZ29vZ2xlLnByb3RvYnVmLm5vX2dlbmVyaWNfc2VydmljZXNf" +
"dGVzdBokZ29vZ2xlL3Byb3RvYnVmL2NzaGFycF9vcHRpb25zLnByb3RvIiMK" +
"C1Rlc3RNZXNzYWdlEgkKAWEYASABKAUqCQjoBxCAgICAAioTCghUZXN0RW51" +
"bRIHCgNGT08QATKCAQoLVGVzdFNlcnZpY2UScwoDRm9vEjUuZ29vZ2xlLnBy" +
"b3RvYnVmLm5vX2dlbmVyaWNfc2VydmljZXNfdGVzdC5UZXN0TWVzc2FnZRo1" +
"Lmdvb2dsZS5wcm90b2J1Zi5ub19nZW5lcmljX3NlcnZpY2VzX3Rlc3QuVGVz" +
"dE1lc3NhZ2U6TgoOdGVzdF9leHRlbnNpb24SNS5nb29nbGUucHJvdG9idWYu" +
"bm9fZ2VuZXJpY19zZXJ2aWNlc190ZXN0LlRlc3RNZXNzYWdlGOgHIAEoBUJk" +
"gAEAiAEAkAEAwj5YCjJHb29nbGUuUHJvdG9jb2xCdWZmZXJzLlRlc3RQcm90" +
"b3MuTm9HZW5lcmljU2VydmljZRIiVW5pdFRlc3ROb0dlbmVyaWNTZXJ2aWNl" +
"c1Byb3RvRmlsZQ==");
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_google_protobuf_no_generic_services_test_TestMessage__Descriptor = Descriptor.MessageTypes[0];
internal__static_google_protobuf_no_generic_services_test_TestMessage__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.TestProtos.NoGenericService.TestMessage, global::Google.ProtocolBuffers.TestProtos.NoGenericService.TestMessage.Builder>(internal__static_google_protobuf_no_generic_services_test_TestMessage__Descriptor,
new string[] { "A", });
global::Google.ProtocolBuffers.TestProtos.NoGenericService.UnitTestNoGenericServicesProtoFile.TestExtension = pb::GeneratedSingleExtension<int>.CreateInstance(global::Google.ProtocolBuffers.TestProtos.NoGenericService.UnitTestNoGenericServicesProtoFile.Descriptor.Extensions[0]);
pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance();
RegisterAllExtensions(registry);
global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.RegisterAllExtensions(registry);
return registry;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.Descriptor,
}, assigner);
}
#endregion
}
#region Enums
public enum TestEnum {
FOO = 1,
}
#endregion
#region Messages
public sealed partial class TestMessage : pb::ExtendableMessage<TestMessage, TestMessage.Builder> {
private static readonly TestMessage defaultInstance = new Builder().BuildPartial();
public static TestMessage DefaultInstance {
get { return defaultInstance; }
}
public override TestMessage DefaultInstanceForType {
get { return defaultInstance; }
}
protected override TestMessage ThisMessage {
get { return this; }
}
public static pbd::MessageDescriptor Descriptor {
get { return global::Google.ProtocolBuffers.TestProtos.NoGenericService.UnitTestNoGenericServicesProtoFile.internal__static_google_protobuf_no_generic_services_test_TestMessage__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<TestMessage, TestMessage.Builder> InternalFieldAccessors {
get { return global::Google.ProtocolBuffers.TestProtos.NoGenericService.UnitTestNoGenericServicesProtoFile.internal__static_google_protobuf_no_generic_services_test_TestMessage__FieldAccessorTable; }
}
public const int AFieldNumber = 1;
private bool hasA;
private int a_ = 0;
public bool HasA {
get { return hasA; }
}
public int A {
get { return a_; }
}
public override bool IsInitialized {
get {
if (!ExtensionsAreInitialized) return false;
return true;
}
}
public override void WriteTo(pb::CodedOutputStream output) {
int size = SerializedSize;
pb::ExtendableMessage<TestMessage, TestMessage.Builder>.ExtensionWriter extensionWriter = CreateExtensionWriter(this);
if (HasA) {
output.WriteInt32(1, A);
}
extensionWriter.WriteUntil(536870912, output);
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (HasA) {
size += pb::CodedOutputStream.ComputeInt32Size(1, A);
}
size += ExtensionsSerializedSize;
size += UnknownFields.SerializedSize;
memoizedSerializedSize = size;
return size;
}
}
public static TestMessage ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static TestMessage ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static TestMessage ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static TestMessage ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static TestMessage ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static TestMessage ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static TestMessage ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static TestMessage ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static TestMessage ParseFrom(pb::CodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static TestMessage ParseFrom(pb::CodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
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(TestMessage prototype) {
return (Builder) new Builder().MergeFrom(prototype);
}
public sealed partial class Builder : pb::ExtendableBuilder<TestMessage, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {}
TestMessage result = new TestMessage();
protected override TestMessage MessageBeingBuilt {
get { return result; }
}
public override Builder Clear() {
result = new TestMessage();
return this;
}
public override Builder Clone() {
return new Builder().MergeFrom(result);
}
public override pbd::MessageDescriptor DescriptorForType {
get { return global::Google.ProtocolBuffers.TestProtos.NoGenericService.TestMessage.Descriptor; }
}
public override TestMessage DefaultInstanceForType {
get { return global::Google.ProtocolBuffers.TestProtos.NoGenericService.TestMessage.DefaultInstance; }
}
public override TestMessage BuildPartial() {
if (result == null) {
throw new global::System.InvalidOperationException("build() has already been called on this Builder");
}
TestMessage returnMe = result;
result = null;
return returnMe;
}
public override Builder MergeFrom(pb::IMessage other) {
if (other is TestMessage) {
return MergeFrom((TestMessage) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(TestMessage other) {
if (other == global::Google.ProtocolBuffers.TestProtos.NoGenericService.TestMessage.DefaultInstance) return this;
if (other.HasA) {
A = other.A;
}
this.MergeExtensionFields(other);
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::CodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::CodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
pb::UnknownFieldSet.Builder unknownFields = null;
while (true) {
uint tag = input.ReadTag();
switch (tag) {
case 0: {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
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);
break;
}
case 8: {
A = input.ReadInt32();
break;
}
}
}
}
public bool HasA {
get { return result.HasA; }
}
public int A {
get { return result.A; }
set { SetA(value); }
}
public Builder SetA(int value) {
result.hasA = true;
result.a_ = value;
return this;
}
public Builder ClearA() {
result.hasA = false;
result.a_ = 0;
return this;
}
}
static TestMessage() {
object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.NoGenericService.UnitTestNoGenericServicesProtoFile.Descriptor, null);
}
}
#endregion
#region Services
public abstract class TestService : pb::IService {
public abstract void Foo(
pb::IRpcController controller,
global::Google.ProtocolBuffers.TestProtos.NoGenericService.TestMessage request,
global::System.Action<global::Google.ProtocolBuffers.TestProtos.NoGenericService.TestMessage> done);
public static pbd::ServiceDescriptor Descriptor {
get { return UnitTestNoGenericServicesProtoFile.Descriptor.Services[0]; }
}
public pbd::ServiceDescriptor DescriptorForType {
get { return Descriptor; }
}
public void CallMethod(
pbd::MethodDescriptor method,
pb::IRpcController controller,
pb::IMessage request,
global::System.Action<pb::IMessage> done) {
if (method.Service != Descriptor) {
throw new global::System.ArgumentException(
"Service.CallMethod() given method descriptor for wrong service type.");
}
switch(method.Index) {
case 0:
this.Foo(controller, (global::Google.ProtocolBuffers.TestProtos.NoGenericService.TestMessage) request,
pb::RpcUtil.SpecializeCallback<global::Google.ProtocolBuffers.TestProtos.NoGenericService.TestMessage>(
done));
return;
default:
throw new global::System.InvalidOperationException("Can't get here.");
}
}
public pb::IMessage GetRequestPrototype(pbd::MethodDescriptor method) {
if (method.Service != Descriptor) {
throw new global::System.ArgumentException(
"Service.GetRequestPrototype() given method descriptor for wrong service type.");
}
switch(method.Index) {
case 0:
return global::Google.ProtocolBuffers.TestProtos.NoGenericService.TestMessage.DefaultInstance;
default:
throw new global::System.InvalidOperationException("Can't get here.");
}
}
public pb::IMessage GetResponsePrototype(pbd::MethodDescriptor method) {
if (method.Service != Descriptor) {
throw new global::System.ArgumentException(
"Service.GetResponsePrototype() given method descriptor for wrong service type.");
}
switch(method.Index) {
case 0:
return global::Google.ProtocolBuffers.TestProtos.NoGenericService.TestMessage.DefaultInstance;
default:
throw new global::System.InvalidOperationException("Can't get here.");
}
}
public static Stub CreateStub(pb::IRpcChannel channel) {
return new Stub(channel);
}
public class Stub : global::Google.ProtocolBuffers.TestProtos.NoGenericService.TestService {
internal Stub(pb::IRpcChannel channel) {
this.channel = channel;
}
private readonly pb::IRpcChannel channel;
public pb::IRpcChannel Channel {
get { return channel; }
}
public override void Foo(
pb::IRpcController controller,
global::Google.ProtocolBuffers.TestProtos.NoGenericService.TestMessage request,
global::System.Action<global::Google.ProtocolBuffers.TestProtos.NoGenericService.TestMessage> done) {
channel.CallMethod(Descriptor.Methods[0],
controller, request, global::Google.ProtocolBuffers.TestProtos.NoGenericService.TestMessage.DefaultInstance,
pb::RpcUtil.GeneralizeCallback<global::Google.ProtocolBuffers.TestProtos.NoGenericService.TestMessage, global::Google.ProtocolBuffers.TestProtos.NoGenericService.TestMessage.Builder>(done, global::Google.ProtocolBuffers.TestProtos.NoGenericService.TestMessage.DefaultInstance));
}
}
}
#endregion
}

@ -1,4 +1,4 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// Generated by ProtoGen, Version=0.9.0.0, Culture=neutral, PublicKeyToken=8fd7408b07f8d2cd. DO NOT EDIT!
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;

File diff suppressed because it is too large Load Diff

@ -1,6 +1,34 @@

Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "proto", "proto", "{1F896D5C-5FC2-4671-9216-781CB8187EC7}"
ProjectSection(SolutionItems) = preProject
..\protos\tutorial\addressbook.proto = ..\protos\tutorial\addressbook.proto
..\protos\google\protobuf\csharp_options.proto = ..\protos\google\protobuf\csharp_options.proto
..\protos\google\protobuf\descriptor.proto = ..\protos\google\protobuf\descriptor.proto
..\ProtocolBuffers.build = ..\ProtocolBuffers.build
..\todo.txt = ..\todo.txt
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "unittest", "unittest", "{C8D3015A-EA39-4F03-AEEC-3FF1F2087A12}"
ProjectSection(SolutionItems) = preProject
..\..\..\DotNet\ProtoFiles\Test\Protos\SampleComplex.proto = ..\..\..\DotNet\ProtoFiles\Test\Protos\SampleComplex.proto
..\protos\google\protobuf\unittest.proto = ..\protos\google\protobuf\unittest.proto
..\protos\google\protobuf\unittest_csharp_options.proto = ..\protos\google\protobuf\unittest_csharp_options.proto
..\protos\google\protobuf\unittest_custom_options.proto = ..\protos\google\protobuf\unittest_custom_options.proto
..\protos\google\protobuf\unittest_embed_optimize_for.proto = ..\protos\google\protobuf\unittest_embed_optimize_for.proto
..\protos\google\protobuf\unittest_empty.proto = ..\protos\google\protobuf\unittest_empty.proto
..\protos\google\protobuf\unittest_enormous_descriptor.proto = ..\protos\google\protobuf\unittest_enormous_descriptor.proto
..\protos\extest\unittest_extras_lite.proto = ..\protos\extest\unittest_extras_lite.proto
..\protos\google\protobuf\unittest_import.proto = ..\protos\google\protobuf\unittest_import.proto
..\protos\google\protobuf\unittest_import_lite.proto = ..\protos\google\protobuf\unittest_import_lite.proto
..\protos\google\protobuf\unittest_lite.proto = ..\protos\google\protobuf\unittest_lite.proto
..\protos\google\protobuf\unittest_lite_imports_nonlite.proto = ..\protos\google\protobuf\unittest_lite_imports_nonlite.proto
..\protos\google\protobuf\unittest_mset.proto = ..\protos\google\protobuf\unittest_mset.proto
..\protos\google\protobuf\unittest_no_generic_services.proto = ..\protos\google\protobuf\unittest_no_generic_services.proto
..\protos\google\protobuf\unittest_optimize_for.proto = ..\protos\google\protobuf\unittest_optimize_for.proto
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProtocolBuffers", "ProtocolBuffers\ProtocolBuffers.csproj", "{6908BDCE-D925-43F3-94AC-A531E6DF2591}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProtocolBuffers.Test", "ProtocolBuffers.Test\ProtocolBuffers.Test.csproj", "{DD01ED24-3750-4567-9A23-1DB676A15610}"
@ -17,13 +45,11 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProtoBench", "ProtoBench\Pr
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProtoDump", "ProtoDump\ProtoDump.csproj", "{D7282E99-2DC3-405B-946F-177DB2FD2AE2}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "proto", "proto", "{1F896D5C-5FC2-4671-9216-781CB8187EC7}"
ProjectSection(SolutionItems) = preProject
..\protos\tutorial\addressbook.proto = ..\protos\tutorial\addressbook.proto
..\protos\google\protobuf\csharp_options.proto = ..\protos\google\protobuf\csharp_options.proto
..\protos\google\protobuf\descriptor.proto = ..\protos\google\protobuf\descriptor.proto
..\todo.txt = ..\todo.txt
EndProjectSection
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProtocolBuffersLite", "ProtocolBuffers\ProtocolBuffersLite.csproj", "{6969BDCE-D925-43F3-94AC-A531E6DF2591}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProtocolBuffersLite.Test", "ProtocolBuffersLite.Test\ProtocolBuffersLite.Test.csproj", "{EE01ED24-3750-4567-9A23-1DB676A15610}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProtocolBuffersLiteMixed.Test", "ProtocolBuffersLite.Test\ProtocolBuffersLiteMixed.Test.csproj", "{EEFFED24-3750-4567-9A23-1DB676A15610}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -97,8 +123,35 @@ Global
{D7282E99-2DC3-405B-946F-177DB2FD2AE2}.Release_Silverlight2|Any CPU.Build.0 = Release_Silverlight2|Any CPU
{D7282E99-2DC3-405B-946F-177DB2FD2AE2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D7282E99-2DC3-405B-946F-177DB2FD2AE2}.Release|Any CPU.Build.0 = Release|Any CPU
{6969BDCE-D925-43F3-94AC-A531E6DF2591}.Debug_Silverlight2|Any CPU.ActiveCfg = Debug_Silverlight2|Any CPU
{6969BDCE-D925-43F3-94AC-A531E6DF2591}.Debug_Silverlight2|Any CPU.Build.0 = Debug_Silverlight2|Any CPU
{6969BDCE-D925-43F3-94AC-A531E6DF2591}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6969BDCE-D925-43F3-94AC-A531E6DF2591}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6969BDCE-D925-43F3-94AC-A531E6DF2591}.Release_Silverlight2|Any CPU.ActiveCfg = Release_Silverlight2|Any CPU
{6969BDCE-D925-43F3-94AC-A531E6DF2591}.Release_Silverlight2|Any CPU.Build.0 = Release_Silverlight2|Any CPU
{6969BDCE-D925-43F3-94AC-A531E6DF2591}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6969BDCE-D925-43F3-94AC-A531E6DF2591}.Release|Any CPU.Build.0 = Release|Any CPU
{EE01ED24-3750-4567-9A23-1DB676A15610}.Debug_Silverlight2|Any CPU.ActiveCfg = Debug_Silverlight2|Any CPU
{EE01ED24-3750-4567-9A23-1DB676A15610}.Debug_Silverlight2|Any CPU.Build.0 = Debug_Silverlight2|Any CPU
{EE01ED24-3750-4567-9A23-1DB676A15610}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EE01ED24-3750-4567-9A23-1DB676A15610}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EE01ED24-3750-4567-9A23-1DB676A15610}.Release_Silverlight2|Any CPU.ActiveCfg = Release_Silverlight2|Any CPU
{EE01ED24-3750-4567-9A23-1DB676A15610}.Release_Silverlight2|Any CPU.Build.0 = Release_Silverlight2|Any CPU
{EE01ED24-3750-4567-9A23-1DB676A15610}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EE01ED24-3750-4567-9A23-1DB676A15610}.Release|Any CPU.Build.0 = Release|Any CPU
{EEFFED24-3750-4567-9A23-1DB676A15610}.Debug_Silverlight2|Any CPU.ActiveCfg = Debug_Silverlight2|Any CPU
{EEFFED24-3750-4567-9A23-1DB676A15610}.Debug_Silverlight2|Any CPU.Build.0 = Debug_Silverlight2|Any CPU
{EEFFED24-3750-4567-9A23-1DB676A15610}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EEFFED24-3750-4567-9A23-1DB676A15610}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EEFFED24-3750-4567-9A23-1DB676A15610}.Release_Silverlight2|Any CPU.ActiveCfg = Release_Silverlight2|Any CPU
{EEFFED24-3750-4567-9A23-1DB676A15610}.Release_Silverlight2|Any CPU.Build.0 = Release_Silverlight2|Any CPU
{EEFFED24-3750-4567-9A23-1DB676A15610}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EEFFED24-3750-4567-9A23-1DB676A15610}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{C8D3015A-EA39-4F03-AEEC-3FF1F2087A12} = {1F896D5C-5FC2-4671-9216-781CB8187EC7}
EndGlobalSection
EndGlobal

@ -42,93 +42,57 @@ namespace Google.ProtocolBuffers {
/// <summary>
/// Implementation of the non-generic IMessage interface as far as possible.
/// </summary>
public abstract class AbstractBuilder<TMessage, TBuilder> : IBuilder<TMessage, TBuilder>
public abstract class AbstractBuilder<TMessage, TBuilder> : AbstractBuilderLite<TMessage, TBuilder>, IBuilder<TMessage, TBuilder>
where TMessage : AbstractMessage<TMessage, TBuilder>
where TBuilder : AbstractBuilder<TMessage, TBuilder> {
protected abstract TBuilder ThisBuilder { get; }
#region Unimplemented members of IBuilder
public abstract UnknownFieldSet UnknownFields { get; set; }
public abstract TBuilder MergeFrom(TMessage other);
public abstract bool IsInitialized { get; }
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 TMessage Build();
public abstract TMessage BuildPartial();
public abstract TBuilder Clone();
public abstract TMessage DefaultInstanceForType { get; }
public abstract IBuilder CreateBuilderForField(FieldDescriptor field);
public abstract TBuilder ClearField(FieldDescriptor field);
public abstract TBuilder AddRepeatedField(FieldDescriptor field, object value);
#endregion
#region Implementation of methods which don't require type parameter information
public IMessage WeakBuild() {
return Build();
}
public IBuilder WeakAddRepeatedField(FieldDescriptor field, object value) {
return AddRepeatedField(field, value);
}
public IBuilder WeakClear() {
return Clear();
}
public IBuilder WeakMergeFrom(IMessage message) {
return MergeFrom(message);
}
public IBuilder WeakMergeFrom(CodedInputStream input) {
return MergeFrom(input);
}
public IBuilder WeakMergeFrom(CodedInputStream input, ExtensionRegistry registry) {
return MergeFrom(input, registry);
}
public IBuilder WeakMergeFrom(ByteString data) {
return MergeFrom(data);
}
public IBuilder WeakMergeFrom(ByteString data, ExtensionRegistry registry) {
return MergeFrom(data, registry);
}
public IMessage WeakBuildPartial() {
return BuildPartial();
}
public IBuilder WeakClone() {
return Clone();
}
public IMessage WeakDefaultInstanceForType {
get { return DefaultInstanceForType; }
}
public IBuilder WeakClearField(FieldDescriptor field) {
return ClearField(field);
}
#endregion
public TBuilder SetUnknownFields(UnknownFieldSet fields) {
UnknownFields = fields;
return ThisBuilder;
}
public virtual TBuilder Clear() {
public override TBuilder Clear() {
foreach(FieldDescriptor field in AllFields.Keys) {
ClearField(field);
}
return ThisBuilder;
}
public sealed override 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.");
@ -151,13 +115,13 @@ namespace Google.ProtocolBuffers {
}
} else if (field.MappedType == MappedType.Message) {
// Merge singular messages
IMessage existingValue = (IMessage) this[field];
IMessageLite existingValue = (IMessageLite)this[field];
if (existingValue == existingValue.WeakDefaultInstanceForType) {
this[field] = entry.Value;
} else {
this[field] = existingValue.WeakCreateBuilderForType()
.WeakMergeFrom(existingValue)
.WeakMergeFrom((IMessage) entry.Value)
.WeakMergeFrom((IMessageLite)entry.Value)
.WeakBuild();
}
} else {
@ -165,14 +129,14 @@ namespace Google.ProtocolBuffers {
this[field] = entry.Value;
}
}
return ThisBuilder;
}
public virtual TBuilder MergeFrom(CodedInputStream input) {
return MergeFrom(input, ExtensionRegistry.Empty);
//Fix for unknown fields not merging, see java's AbstractMessage.Builder<T> line 236
MergeUnknownFields(other.UnknownFields);
return ThisBuilder;
}
public virtual TBuilder MergeFrom(CodedInputStream input, ExtensionRegistry extensionRegistry) {
public override TBuilder MergeFrom(CodedInputStream input, ExtensionRegistry extensionRegistry) {
UnknownFieldSet.Builder unknownFields = UnknownFieldSet.CreateBuilder(UnknownFields);
unknownFields.MergeFrom(input, extensionRegistry, this);
UnknownFields = unknownFields.Build();
@ -186,131 +150,65 @@ namespace Google.ProtocolBuffers {
return ThisBuilder;
}
public virtual TBuilder MergeFrom(ByteString data) {
CodedInputStream input = data.CreateCodedInput();
MergeFrom(input);
input.CheckLastTagWas(0);
public virtual IBuilder SetField(FieldDescriptor field, object value) {
this[field] = value;
return ThisBuilder;
}
public virtual TBuilder MergeFrom(ByteString data, ExtensionRegistry extensionRegistry) {
CodedInputStream input = data.CreateCodedInput();
MergeFrom(input, extensionRegistry);
input.CheckLastTagWas(0);
public virtual IBuilder SetRepeatedField(FieldDescriptor field, int index, object value) {
this[field, index] = value;
return ThisBuilder;
}
}
public virtual TBuilder MergeFrom(byte[] data) {
CodedInputStream input = CodedInputStream.CreateInstance(data);
MergeFrom(input);
input.CheckLastTagWas(0);
return ThisBuilder;
}
#region Explicit Implementations
public virtual TBuilder MergeFrom(byte[] data, ExtensionRegistry extensionRegistry) {
CodedInputStream input = CodedInputStream.CreateInstance(data);
MergeFrom(input, extensionRegistry);
input.CheckLastTagWas(0);
return ThisBuilder;
IMessage IBuilder.WeakBuild() {
return Build();
}
public virtual TBuilder MergeFrom(Stream input) {
CodedInputStream codedInput = CodedInputStream.CreateInstance(input);
MergeFrom(codedInput);
codedInput.CheckLastTagWas(0);
return ThisBuilder;
IBuilder IBuilder.WeakAddRepeatedField(FieldDescriptor field, object value) {
return AddRepeatedField(field, value);
}
public virtual TBuilder MergeFrom(Stream input, ExtensionRegistry extensionRegistry) {
CodedInputStream codedInput = CodedInputStream.CreateInstance(input);
MergeFrom(codedInput, extensionRegistry);
codedInput.CheckLastTagWas(0);
return ThisBuilder;
IBuilder IBuilder.WeakClear() {
return Clear();
}
public TBuilder MergeDelimitedFrom(Stream input, ExtensionRegistry extensionRegistry) {
int size = (int) CodedInputStream.ReadRawVarint32(input);
Stream limitedStream = new LimitedInputStream(input, size);
return MergeFrom(limitedStream, extensionRegistry);
IBuilder IBuilder.WeakMergeFrom(IMessage message) {
return MergeFrom(message);
}
public TBuilder MergeDelimitedFrom(Stream input) {
return MergeDelimitedFrom(input, ExtensionRegistry.Empty);
IBuilder IBuilder.WeakMergeFrom(CodedInputStream input) {
return MergeFrom(input);
}
public virtual IBuilder SetField(FieldDescriptor field, object value) {
this[field] = value;
return ThisBuilder;
IBuilder IBuilder.WeakMergeFrom(CodedInputStream input, ExtensionRegistry registry) {
return MergeFrom(input, registry);
}
public virtual IBuilder SetRepeatedField(FieldDescriptor field, int index, object value) {
this[field, index] = value;
return ThisBuilder;
IBuilder IBuilder.WeakMergeFrom(ByteString data) {
return MergeFrom(data);
}
/// <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 NotImplementedException(); }
}
public override long Position {
get {
throw new NotImplementedException();
}
set {
throw new NotImplementedException();
}
}
IBuilder IBuilder.WeakMergeFrom(ByteString data, ExtensionRegistry registry) {
return MergeFrom(data, registry);
}
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;
}
IMessage IBuilder.WeakBuildPartial() {
return BuildPartial();
}
public override long Seek(long offset, SeekOrigin origin) {
throw new NotImplementedException();
}
IBuilder IBuilder.WeakClone() {
return Clone();
}
public override void SetLength(long value) {
throw new NotImplementedException();
}
IMessage IBuilder.WeakDefaultInstanceForType {
get { return DefaultInstanceForType; }
}
public override void Write(byte[] buffer, int offset, int count) {
throw new NotImplementedException();
}
IBuilder IBuilder.WeakClearField(FieldDescriptor field) {
return ClearField(field);
}
#endregion
}
}

@ -0,0 +1,232 @@
#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 System.IO;
namespace Google.ProtocolBuffers {
/// <summary>
/// Implementation of the non-generic IMessage interface as far as possible.
/// </summary>
public abstract 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(CodedInputStream input, ExtensionRegistry extensionRegistry);
public abstract TMessage DefaultInstanceForType { get; }
#region IBuilderLite<TMessage,TBuilder> Members
public virtual TBuilder MergeFrom(CodedInputStream 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(CodedInputStream input) {
return MergeFrom(input);
}
IBuilderLite IBuilderLite.WeakMergeFrom(CodedInputStream 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
}
}

@ -42,7 +42,7 @@ namespace Google.ProtocolBuffers {
/// <summary>
/// Implementation of the non-generic IMessage interface as far as possible.
/// </summary>
public abstract class AbstractMessage<TMessage, TBuilder> : IMessage<TMessage, TBuilder>
public abstract class AbstractMessage<TMessage, TBuilder> : AbstractMessageLite<TMessage, TBuilder>, IMessage<TMessage, TBuilder>
where TMessage : AbstractMessage<TMessage, TBuilder>
where TBuilder : AbstractBuilder<TMessage, TBuilder> {
/// <summary>
@ -59,24 +59,13 @@ namespace Google.ProtocolBuffers {
public abstract int GetRepeatedFieldCount(FieldDescriptor field);
public abstract object this[FieldDescriptor field, int index] { get; }
public abstract UnknownFieldSet UnknownFields { get; }
public abstract TMessage DefaultInstanceForType { get; }
public abstract TBuilder CreateBuilderForType();
public abstract TBuilder ToBuilder();
#endregion
public IBuilder WeakCreateBuilderForType() {
return CreateBuilderForType();
}
public IBuilder WeakToBuilder() {
return ToBuilder();
}
public IMessage WeakDefaultInstanceForType {
get { return DefaultInstanceForType; }
}
public virtual bool IsInitialized {
/// <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) {
@ -92,13 +81,13 @@ namespace Google.ProtocolBuffers {
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 (IMessage element in (IEnumerable) entry.Value) {
foreach (IMessageLite element in (IEnumerable)entry.Value) {
if (!element.IsInitialized) {
return false;
}
}
} else {
if (!((IMessage)entry.Value).IsInitialized) {
if (!((IMessageLite)entry.Value).IsInitialized) {
return false;
}
}
@ -112,7 +101,23 @@ namespace Google.ProtocolBuffers {
return TextFormat.PrintToString(this);
}
public virtual void WriteTo(CodedOutputStream output) {
public sealed override 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(CodedOutputStream output) {
foreach (KeyValuePair<FieldDescriptor, object> entry in AllFields) {
FieldDescriptor field = entry.Key;
if (field.IsRepeated) {
@ -147,7 +152,11 @@ namespace Google.ProtocolBuffers {
}
}
public virtual int SerializedSize {
/// <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;
@ -188,33 +197,12 @@ namespace Google.ProtocolBuffers {
}
}
public ByteString ToByteString() {
ByteString.CodedBuilder output = new ByteString.CodedBuilder(SerializedSize);
WriteTo(output.CodedOutput);
return output.Build();
}
public byte[] ToByteArray() {
byte[] result = new byte[SerializedSize];
CodedOutputStream output = CodedOutputStream.CreateInstance(result);
WriteTo(output);
output.CheckNoSpaceLeft();
return result;
}
public void WriteTo(Stream output) {
CodedOutputStream codedOutput = CodedOutputStream.CreateInstance(output);
WriteTo(codedOutput);
codedOutput.Flush();
}
public void WriteDelimitedTo(Stream output) {
CodedOutputStream codedOutput = CodedOutputStream.CreateInstance(output);
codedOutput.WriteRawVarint32((uint) SerializedSize);
WriteTo(codedOutput);
codedOutput.Flush();
}
/// <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;
@ -226,6 +214,10 @@ namespace Google.ProtocolBuffers {
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();
@ -233,5 +225,21 @@ namespace Google.ProtocolBuffers {
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
}
}

@ -0,0 +1,133 @@
#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;
namespace Google.ProtocolBuffers {
/// <summary>
/// Implementation of the non-generic IMessage interface as far as possible.
/// </summary>
public abstract 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(CodedOutputStream 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(CodedOutputStream).
/// </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(CodedOutputStream).
/// </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
}
}

@ -78,6 +78,13 @@ namespace Google.ProtocolBuffers {
return (byte[])bytes.Clone();
}
/// <summary>
/// Constructs a ByteString from the Base64 Encoded String.
/// </summary>
public static ByteString FromBase64(string bytes) {
return new ByteString(System.Convert.FromBase64String(bytes));
}
/// <summary>
/// Constructs a ByteString from the given array. The contents
/// are copied, so further modifications to the array will not

@ -258,7 +258,7 @@ namespace Google.ProtocolBuffers {
/// <summary>
/// Reads a group field value from the stream.
/// </summary>
public void ReadGroup(int fieldNumber, IBuilder builder,
public void ReadGroup(int fieldNumber, IBuilderLite builder,
ExtensionRegistry extensionRegistry) {
if (recursionDepth >= recursionLimit) {
throw InvalidProtocolBufferException.RecursionLimitExceeded();
@ -273,12 +273,14 @@ namespace Google.ProtocolBuffers {
/// Reads a group field value from the stream and merges it into the given
/// UnknownFieldSet.
/// </summary>
public void ReadUnknownGroup(int fieldNumber, UnknownFieldSet.Builder builder) {
[Obsolete]
public void ReadUnknownGroup(int fieldNumber, IBuilderLite builder)
{
if (recursionDepth >= recursionLimit) {
throw InvalidProtocolBufferException.RecursionLimitExceeded();
}
++recursionDepth;
builder.MergeFrom(this);
builder.WeakMergeFrom(this);
CheckLastTagWas(WireFormat.MakeTag(fieldNumber, WireFormat.WireType.EndGroup));
--recursionDepth;
}
@ -286,7 +288,7 @@ namespace Google.ProtocolBuffers {
/// <summary>
/// Reads an embedded message field value from the stream.
/// </summary>
public void ReadMessage(IBuilder builder, ExtensionRegistry extensionRegistry) {
public void ReadMessage(IBuilderLite builder, ExtensionRegistry extensionRegistry) {
int length = (int) ReadRawVarint32();
if (recursionDepth >= recursionLimit) {
throw InvalidProtocolBufferException.RecursionLimitExceeded();
@ -393,7 +395,6 @@ namespace Google.ProtocolBuffers {
throw new ArgumentOutOfRangeException("Invalid field type " + fieldType);
}
}
#endregion
#region Underlying reading primitives

@ -206,19 +206,20 @@ namespace Google.ProtocolBuffers {
/// <summary>
/// Writes a group field value, including tag, to the stream.
/// </summary>
public void WriteGroup(int fieldNumber, IMessage value) {
public void WriteGroup(int fieldNumber, IMessageLite value) {
WriteTag(fieldNumber, WireFormat.WireType.StartGroup);
value.WriteTo(this);
WriteTag(fieldNumber, WireFormat.WireType.EndGroup);
}
public void WriteUnknownGroup(int fieldNumber, UnknownFieldSet value) {
[Obsolete]
public void WriteUnknownGroup(int fieldNumber, IMessageLite value) {
WriteTag(fieldNumber, WireFormat.WireType.StartGroup);
value.WriteTo(this);
WriteTag(fieldNumber, WireFormat.WireType.EndGroup);
}
public void WriteMessage(int fieldNumber, IMessage value) {
public void WriteMessage(int fieldNumber, IMessageLite value) {
WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited);
WriteRawVarint32((uint)value.SerializedSize);
value.WriteTo(this);
@ -263,7 +264,7 @@ namespace Google.ProtocolBuffers {
WriteRawVarint64(EncodeZigZag64(value));
}
public void WriteMessageSetExtension(int fieldNumber, IMessage value) {
public void WriteMessageSetExtension(int fieldNumber, IMessageLite value) {
WriteTag(WireFormat.MessageSetField.Item, WireFormat.WireType.StartGroup);
WriteUInt32(WireFormat.MessageSetField.TypeID, (uint)fieldNumber);
WriteMessage(WireFormat.MessageSetField.Message, value);
@ -288,15 +289,15 @@ namespace Google.ProtocolBuffers {
case FieldType.Fixed32: WriteFixed32(fieldNumber, (uint)value); break;
case FieldType.Bool: WriteBool(fieldNumber, (bool)value); break;
case FieldType.String: WriteString(fieldNumber, (string)value); break;
case FieldType.Group: WriteGroup(fieldNumber, (IMessage)value); break;
case FieldType.Message: WriteMessage(fieldNumber, (IMessage)value); break;
case FieldType.Group: WriteGroup(fieldNumber, (IMessageLite)value); break;
case FieldType.Message: WriteMessage(fieldNumber, (IMessageLite)value); break;
case FieldType.Bytes: WriteBytes(fieldNumber, (ByteString)value); break;
case FieldType.UInt32: WriteUInt32(fieldNumber, (uint)value); break;
case FieldType.SFixed32: WriteSFixed32(fieldNumber, (int)value); break;
case FieldType.SFixed64: WriteSFixed64(fieldNumber, (long)value); break;
case FieldType.SInt32: WriteSInt32(fieldNumber, (int)value); break;
case FieldType.SInt64: WriteSInt64(fieldNumber, (long)value); break;
case FieldType.Enum: WriteEnum(fieldNumber, ((EnumValueDescriptor)value).Number);
case FieldType.Enum: WriteEnum(fieldNumber, ((IEnumLite)value).Number);
break;
}
}
@ -312,15 +313,15 @@ namespace Google.ProtocolBuffers {
case FieldType.Fixed32: WriteFixed32NoTag((uint)value); break;
case FieldType.Bool: WriteBoolNoTag((bool)value); break;
case FieldType.String: WriteStringNoTag((string)value); break;
case FieldType.Group: WriteGroupNoTag((IMessage)value); break;
case FieldType.Message: WriteMessageNoTag((IMessage)value); break;
case FieldType.Group: WriteGroupNoTag((IMessageLite)value); break;
case FieldType.Message: WriteMessageNoTag((IMessageLite)value); break;
case FieldType.Bytes: WriteBytesNoTag((ByteString)value); break;
case FieldType.UInt32: WriteUInt32NoTag((uint)value); break;
case FieldType.SFixed32: WriteSFixed32NoTag((int)value); break;
case FieldType.SFixed64: WriteSFixed64NoTag((long)value); break;
case FieldType.SInt32: WriteSInt32NoTag((int)value); break;
case FieldType.SInt64: WriteSInt64NoTag((long)value); break;
case FieldType.Enum: WriteEnumNoTag(((EnumValueDescriptor)value).Number);
case FieldType.Enum: WriteEnumNoTag(((IEnumLite)value).Number);
break;
}
}
@ -420,11 +421,11 @@ namespace Google.ProtocolBuffers {
/// <summary>
/// Writes a group field value, without a tag, to the stream.
/// </summary>
public void WriteGroupNoTag(IMessage value) {
public void WriteGroupNoTag(IMessageLite value) {
value.WriteTo(this);
}
public void WriteMessageNoTag(IMessage value) {
public void WriteMessageNoTag(IMessageLite value) {
WriteRawVarint32((uint)value.SerializedSize);
value.WriteTo(this);
}
@ -685,7 +686,7 @@ 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, IMessage value) {
public static int ComputeGroupSize(int fieldNumber, IMessageLite value) {
return ComputeTagSize(fieldNumber) * 2 + value.SerializedSize;
}
@ -693,8 +694,9 @@ namespace Google.ProtocolBuffers {
/// 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 ComputeUnknownGroupSize(int fieldNumber,
UnknownFieldSet value) {
IMessageLite value) {
return ComputeTagSize(fieldNumber) * 2 + value.SerializedSize;
}
@ -702,7 +704,7 @@ namespace Google.ProtocolBuffers {
/// 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, IMessage value) {
public static int ComputeMessageSize(int fieldNumber, IMessageLite value) {
int size = value.SerializedSize;
return ComputeTagSize(fieldNumber) + ComputeRawVarint32Size((uint)size) + size;
}
@ -853,7 +855,7 @@ 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(IMessage value) {
public static int ComputeGroupSizeNoTag(IMessageLite value) {
return value.SerializedSize;
}
@ -861,7 +863,8 @@ namespace Google.ProtocolBuffers {
/// Compute the number of bytes that would be needed to encode a
/// group field represented by an UnknownFieldSet, including the tag.
/// </summary>
public static int ComputeUnknownGroupSizeNoTag(UnknownFieldSet value) {
[Obsolete]
public static int ComputeUnknownGroupSizeNoTag(IMessageLite value) {
return value.SerializedSize;
}
@ -869,7 +872,7 @@ namespace Google.ProtocolBuffers {
/// Compute the number of bytes that would be needed to encode an
/// embedded message field, including the tag.
/// </summary>
public static int ComputeMessageSizeNoTag(IMessage value) {
public static int ComputeMessageSizeNoTag(IMessageLite value) {
int size = value.SerializedSize;
return ComputeRawVarint32Size((uint)size) + size;
}
@ -943,7 +946,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, IMessage value) {
public static int ComputeMessageSetExtensionSize(int fieldNumber, IMessageLite value) {
return ComputeTagSize(WireFormat.MessageSetField.Item) * 2 +
ComputeUInt32Size(WireFormat.MessageSetField.TypeID, (uint) fieldNumber) +
ComputeMessageSize(WireFormat.MessageSetField.Message, value);
@ -1004,15 +1007,15 @@ namespace Google.ProtocolBuffers {
case FieldType.Fixed32: return ComputeFixed32Size(fieldNumber, (uint)value);
case FieldType.Bool: return ComputeBoolSize(fieldNumber, (bool)value);
case FieldType.String: return ComputeStringSize(fieldNumber, (string)value);
case FieldType.Group: return ComputeGroupSize(fieldNumber, (IMessage)value);
case FieldType.Message: return ComputeMessageSize(fieldNumber, (IMessage)value);
case FieldType.Group: return ComputeGroupSize(fieldNumber, (IMessageLite)value);
case FieldType.Message: return ComputeMessageSize(fieldNumber, (IMessageLite)value);
case FieldType.Bytes: return ComputeBytesSize(fieldNumber, (ByteString)value);
case FieldType.UInt32: return ComputeUInt32Size(fieldNumber, (uint)value);
case FieldType.SFixed32: return ComputeSFixed32Size(fieldNumber, (int)value);
case FieldType.SFixed64: return ComputeSFixed64Size(fieldNumber, (long)value);
case FieldType.SInt32: return ComputeSInt32Size(fieldNumber, (int)value);
case FieldType.SInt64: return ComputeSInt64Size(fieldNumber, (long)value);
case FieldType.Enum: return ComputeEnumSize(fieldNumber, ((EnumValueDescriptor)value).Number);
case FieldType.Enum: return ComputeEnumSize(fieldNumber, ((IEnumLite)value).Number);
default:
throw new ArgumentOutOfRangeException("Invalid field type " + fieldType);
}
@ -1033,15 +1036,15 @@ namespace Google.ProtocolBuffers {
case FieldType.Fixed32: return ComputeFixed32SizeNoTag((uint)value);
case FieldType.Bool: return ComputeBoolSizeNoTag((bool)value);
case FieldType.String: return ComputeStringSizeNoTag((string)value);
case FieldType.Group: return ComputeGroupSizeNoTag((IMessage)value);
case FieldType.Message: return ComputeMessageSizeNoTag((IMessage)value);
case FieldType.Group: return ComputeGroupSizeNoTag((IMessageLite)value);
case FieldType.Message: return ComputeMessageSizeNoTag((IMessageLite)value);
case FieldType.Bytes: return ComputeBytesSizeNoTag((ByteString)value);
case FieldType.UInt32: return ComputeUInt32SizeNoTag((uint)value);
case FieldType.SFixed32: return ComputeSFixed32SizeNoTag((int)value);
case FieldType.SFixed64: return ComputeSFixed64SizeNoTag((long)value);
case FieldType.SInt32: return ComputeSInt32SizeNoTag((int)value);
case FieldType.SInt64: return ComputeSInt64SizeNoTag((long)value);
case FieldType.Enum: return ComputeEnumSizeNoTag(((EnumValueDescriptor)value).Number);
case FieldType.Enum: return ComputeEnumSizeNoTag(((IEnumLite)value).Number);
default:
throw new ArgumentOutOfRangeException("Invalid field type " + fieldType);
}

@ -1,4 +1,4 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// Generated by ProtoGen, Version=0.9.0.0, Culture=neutral, PublicKeyToken=8fd7408b07f8d2cd. DO NOT EDIT!
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;

@ -1,4 +1,4 @@
// Generated by the protocol buffer compiler. DO NOT EDIT!
// Generated by ProtoGen, Version=0.9.0.0, Culture=neutral, PublicKeyToken=8fd7408b07f8d2cd. DO NOT EDIT!
using pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections;
@ -104,38 +104,42 @@ namespace Google.ProtocolBuffers.DescriptorProtos {
"Lmdvb2dsZS5wcm90b2J1Zi5TZXJ2aWNlT3B0aW9ucyJ/ChVNZXRob2REZXNj" +
"cmlwdG9yUHJvdG8SDAoEbmFtZRgBIAEoCRISCgppbnB1dF90eXBlGAIgASgJ" +
"EhMKC291dHB1dF90eXBlGAMgASgJEi8KB29wdGlvbnMYBCABKAsyHi5nb29n" +
"bGUucHJvdG9idWYuTWV0aG9kT3B0aW9ucyKnAgoLRmlsZU9wdGlvbnMSFAoM" +
"bGUucHJvdG9idWYuTWV0aG9kT3B0aW9ucyKkAwoLRmlsZU9wdGlvbnMSFAoM" +
"amF2YV9wYWNrYWdlGAEgASgJEhwKFGphdmFfb3V0ZXJfY2xhc3NuYW1lGAgg" +
"ASgJEiIKE2phdmFfbXVsdGlwbGVfZmlsZXMYCiABKAg6BWZhbHNlEkYKDG9w" +
"dGltaXplX2ZvchgJIAEoDjIpLmdvb2dsZS5wcm90b2J1Zi5GaWxlT3B0aW9u" +
"cy5PcHRpbWl6ZU1vZGU6BVNQRUVEEkMKFHVuaW50ZXJwcmV0ZWRfb3B0aW9u" +
"GOcHIAMoCzIkLmdvb2dsZS5wcm90b2J1Zi5VbmludGVycHJldGVkT3B0aW9u" +
"IigKDE9wdGltaXplTW9kZRIJCgVTUEVFRBABEg0KCUNPREVfU0laRRACKgkI" +
"6AcQgICAgAIiiAEKDk1lc3NhZ2VPcHRpb25zEiYKF21lc3NhZ2Vfc2V0X3dp" +
"cmVfZm9ybWF0GAEgASgIOgVmYWxzZRJDChR1bmludGVycHJldGVkX29wdGlv" +
"bhjnByADKAsyJC5nb29nbGUucHJvdG9idWYuVW5pbnRlcnByZXRlZE9wdGlv" +
"bioJCOgHEICAgIACIoACCgxGaWVsZE9wdGlvbnMSMgoFY3R5cGUYASABKA4y" +
"Iy5nb29nbGUucHJvdG9idWYuRmllbGRPcHRpb25zLkNUeXBlEg4KBnBhY2tl" +
"ZBgCIAEoCBIZCgpkZXByZWNhdGVkGAMgASgIOgVmYWxzZRIcChRleHBlcmlt" +
"ZW50YWxfbWFwX2tleRgJIAEoCRJDChR1bmludGVycHJldGVkX29wdGlvbhjn" +
"ByADKAsyJC5nb29nbGUucHJvdG9idWYuVW5pbnRlcnByZXRlZE9wdGlvbiIj" +
"CgVDVHlwZRIICgRDT1JEEAESEAoMU1RSSU5HX1BJRUNFEAIqCQjoBxCAgICA" +
"AiJdCgtFbnVtT3B0aW9ucxJDChR1bmludGVycHJldGVkX29wdGlvbhjnByAD" +
"KAsyJC5nb29nbGUucHJvdG9idWYuVW5pbnRlcnByZXRlZE9wdGlvbioJCOgH" +
"EICAgIACImIKEEVudW1WYWx1ZU9wdGlvbnMSQwoUdW5pbnRlcnByZXRlZF9v" +
"cHRpb24Y5wcgAygLMiQuZ29vZ2xlLnByb3RvYnVmLlVuaW50ZXJwcmV0ZWRP" +
"cHRpb24qCQjoBxCAgICAAiJgCg5TZXJ2aWNlT3B0aW9ucxJDChR1bmludGVy" +
"cHJldGVkX29wdGlvbhjnByADKAsyJC5nb29nbGUucHJvdG9idWYuVW5pbnRl" +
"cnByZXRlZE9wdGlvbioJCOgHEICAgIACIl8KDU1ldGhvZE9wdGlvbnMSQwoU" +
"dW5pbnRlcnByZXRlZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xlLnByb3RvYnVm" +
"LlVuaW50ZXJwcmV0ZWRPcHRpb24qCQjoBxCAgICAAiKFAgoTVW5pbnRlcnBy" +
"ZXRlZE9wdGlvbhI7CgRuYW1lGAIgAygLMi0uZ29vZ2xlLnByb3RvYnVmLlVu" +
"aW50ZXJwcmV0ZWRPcHRpb24uTmFtZVBhcnQSGAoQaWRlbnRpZmllcl92YWx1" +
"ZRgDIAEoCRIaChJwb3NpdGl2ZV9pbnRfdmFsdWUYBCABKAQSGgoSbmVnYXRp" +
"dmVfaW50X3ZhbHVlGAUgASgDEhQKDGRvdWJsZV92YWx1ZRgGIAEoARIUCgxz" +
"dHJpbmdfdmFsdWUYByABKAwaMwoITmFtZVBhcnQSEQoJbmFtZV9wYXJ0GAEg" +
"AigJEhQKDGlzX2V4dGVuc2lvbhgCIAIoCEIpChNjb20uZ29vZ2xlLnByb3Rv" +
"YnVmQhBEZXNjcmlwdG9yUHJvdG9zSAE=");
"cy5PcHRpbWl6ZU1vZGU6BVNQRUVEEiEKE2NjX2dlbmVyaWNfc2VydmljZXMY" +
"ECABKAg6BHRydWUSIwoVamF2YV9nZW5lcmljX3NlcnZpY2VzGBEgASgIOgR0" +
"cnVlEiEKE3B5X2dlbmVyaWNfc2VydmljZXMYEiABKAg6BHRydWUSQwoUdW5p" +
"bnRlcnByZXRlZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xlLnByb3RvYnVmLlVu" +
"aW50ZXJwcmV0ZWRPcHRpb24iOgoMT3B0aW1pemVNb2RlEgkKBVNQRUVEEAES" +
"DQoJQ09ERV9TSVpFEAISEAoMTElURV9SVU5USU1FEAMqCQjoBxCAgICAAiK4" +
"AQoOTWVzc2FnZU9wdGlvbnMSJgoXbWVzc2FnZV9zZXRfd2lyZV9mb3JtYXQY" +
"ASABKAg6BWZhbHNlEi4KH25vX3N0YW5kYXJkX2Rlc2NyaXB0b3JfYWNjZXNz" +
"b3IYAiABKAg6BWZhbHNlEkMKFHVuaW50ZXJwcmV0ZWRfb3B0aW9uGOcHIAMo" +
"CzIkLmdvb2dsZS5wcm90b2J1Zi5VbmludGVycHJldGVkT3B0aW9uKgkI6AcQ" +
"gICAgAIilAIKDEZpZWxkT3B0aW9ucxI6CgVjdHlwZRgBIAEoDjIjLmdvb2ds" +
"ZS5wcm90b2J1Zi5GaWVsZE9wdGlvbnMuQ1R5cGU6BlNUUklORxIOCgZwYWNr" +
"ZWQYAiABKAgSGQoKZGVwcmVjYXRlZBgDIAEoCDoFZmFsc2USHAoUZXhwZXJp" +
"bWVudGFsX21hcF9rZXkYCSABKAkSQwoUdW5pbnRlcnByZXRlZF9vcHRpb24Y" +
"5wcgAygLMiQuZ29vZ2xlLnByb3RvYnVmLlVuaW50ZXJwcmV0ZWRPcHRpb24i" +
"LwoFQ1R5cGUSCgoGU1RSSU5HEAASCAoEQ09SRBABEhAKDFNUUklOR19QSUVD" +
"RRACKgkI6AcQgICAgAIiXQoLRW51bU9wdGlvbnMSQwoUdW5pbnRlcnByZXRl" +
"ZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xlLnByb3RvYnVmLlVuaW50ZXJwcmV0" +
"ZWRPcHRpb24qCQjoBxCAgICAAiJiChBFbnVtVmFsdWVPcHRpb25zEkMKFHVu" +
"aW50ZXJwcmV0ZWRfb3B0aW9uGOcHIAMoCzIkLmdvb2dsZS5wcm90b2J1Zi5V" +
"bmludGVycHJldGVkT3B0aW9uKgkI6AcQgICAgAIiYAoOU2VydmljZU9wdGlv" +
"bnMSQwoUdW5pbnRlcnByZXRlZF9vcHRpb24Y5wcgAygLMiQuZ29vZ2xlLnBy" +
"b3RvYnVmLlVuaW50ZXJwcmV0ZWRPcHRpb24qCQjoBxCAgICAAiJfCg1NZXRo" +
"b2RPcHRpb25zEkMKFHVuaW50ZXJwcmV0ZWRfb3B0aW9uGOcHIAMoCzIkLmdv" +
"b2dsZS5wcm90b2J1Zi5VbmludGVycHJldGVkT3B0aW9uKgkI6AcQgICAgAIi" +
"hQIKE1VuaW50ZXJwcmV0ZWRPcHRpb24SOwoEbmFtZRgCIAMoCzItLmdvb2ds" +
"ZS5wcm90b2J1Zi5VbmludGVycHJldGVkT3B0aW9uLk5hbWVQYXJ0EhgKEGlk" +
"ZW50aWZpZXJfdmFsdWUYAyABKAkSGgoScG9zaXRpdmVfaW50X3ZhbHVlGAQg" +
"ASgEEhoKEm5lZ2F0aXZlX2ludF92YWx1ZRgFIAEoAxIUCgxkb3VibGVfdmFs" +
"dWUYBiABKAESFAoMc3RyaW5nX3ZhbHVlGAcgASgMGjMKCE5hbWVQYXJ0EhEK" +
"CW5hbWVfcGFydBgBIAIoCRIUCgxpc19leHRlbnNpb24YAiACKAhCKQoTY29t" +
"Lmdvb2dsZS5wcm90b2J1ZkIQRGVzY3JpcHRvclByb3Rvc0gB");
pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) {
descriptor = root;
internal__static_google_protobuf_FileDescriptorSet__Descriptor = Descriptor.MessageTypes[0];
@ -177,11 +181,11 @@ namespace Google.ProtocolBuffers.DescriptorProtos {
internal__static_google_protobuf_FileOptions__Descriptor = Descriptor.MessageTypes[8];
internal__static_google_protobuf_FileOptions__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.DescriptorProtos.FileOptions, global::Google.ProtocolBuffers.DescriptorProtos.FileOptions.Builder>(internal__static_google_protobuf_FileOptions__Descriptor,
new string[] { "JavaPackage", "JavaOuterClassname", "JavaMultipleFiles", "OptimizeFor", "UninterpretedOption", });
new string[] { "JavaPackage", "JavaOuterClassname", "JavaMultipleFiles", "OptimizeFor", "CcGenericServices", "JavaGenericServices", "PyGenericServices", "UninterpretedOption", });
internal__static_google_protobuf_MessageOptions__Descriptor = Descriptor.MessageTypes[9];
internal__static_google_protobuf_MessageOptions__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.DescriptorProtos.MessageOptions, global::Google.ProtocolBuffers.DescriptorProtos.MessageOptions.Builder>(internal__static_google_protobuf_MessageOptions__Descriptor,
new string[] { "MessageSetWireFormat", "UninterpretedOption", });
new string[] { "MessageSetWireFormat", "NoStandardDescriptorAccessor", "UninterpretedOption", });
internal__static_google_protobuf_FieldOptions__Descriptor = Descriptor.MessageTypes[10];
internal__static_google_protobuf_FieldOptions__FieldAccessorTable =
new pb::FieldAccess.FieldAccessorTable<global::Google.ProtocolBuffers.DescriptorProtos.FieldOptions, global::Google.ProtocolBuffers.DescriptorProtos.FieldOptions.Builder>(internal__static_google_protobuf_FieldOptions__Descriptor,
@ -4013,6 +4017,7 @@ namespace Google.ProtocolBuffers.DescriptorProtos {
public enum OptimizeMode {
SPEED = 1,
CODE_SIZE = 2,
LITE_RUNTIME = 3,
}
}
@ -4058,6 +4063,36 @@ namespace Google.ProtocolBuffers.DescriptorProtos {
get { return optimizeFor_; }
}
public const int CcGenericServicesFieldNumber = 16;
private bool hasCcGenericServices;
private bool ccGenericServices_ = true;
public bool HasCcGenericServices {
get { return hasCcGenericServices; }
}
public bool CcGenericServices {
get { return ccGenericServices_; }
}
public const int JavaGenericServicesFieldNumber = 17;
private bool hasJavaGenericServices;
private bool javaGenericServices_ = true;
public bool HasJavaGenericServices {
get { return hasJavaGenericServices; }
}
public bool JavaGenericServices {
get { return javaGenericServices_; }
}
public const int PyGenericServicesFieldNumber = 18;
private bool hasPyGenericServices;
private bool pyGenericServices_ = true;
public bool HasPyGenericServices {
get { return hasPyGenericServices; }
}
public bool PyGenericServices {
get { return pyGenericServices_; }
}
public const int UninterpretedOptionFieldNumber = 999;
private pbc::PopsicleList<global::Google.ProtocolBuffers.DescriptorProtos.UninterpretedOption> uninterpretedOption_ = new pbc::PopsicleList<global::Google.ProtocolBuffers.DescriptorProtos.UninterpretedOption>();
public scg::IList<global::Google.ProtocolBuffers.DescriptorProtos.UninterpretedOption> UninterpretedOptionList {
@ -4095,6 +4130,15 @@ namespace Google.ProtocolBuffers.DescriptorProtos {
if (HasJavaMultipleFiles) {
output.WriteBool(10, JavaMultipleFiles);
}
if (HasCcGenericServices) {
output.WriteBool(16, CcGenericServices);
}
if (HasJavaGenericServices) {
output.WriteBool(17, JavaGenericServices);
}
if (HasPyGenericServices) {
output.WriteBool(18, PyGenericServices);
}
foreach (global::Google.ProtocolBuffers.DescriptorProtos.UninterpretedOption element in UninterpretedOptionList) {
output.WriteMessage(999, element);
}
@ -4121,6 +4165,15 @@ namespace Google.ProtocolBuffers.DescriptorProtos {
if (HasOptimizeFor) {
size += pb::CodedOutputStream.ComputeEnumSize(9, (int) OptimizeFor);
}
if (HasCcGenericServices) {
size += pb::CodedOutputStream.ComputeBoolSize(16, CcGenericServices);
}
if (HasJavaGenericServices) {
size += pb::CodedOutputStream.ComputeBoolSize(17, JavaGenericServices);
}
if (HasPyGenericServices) {
size += pb::CodedOutputStream.ComputeBoolSize(18, PyGenericServices);
}
foreach (global::Google.ProtocolBuffers.DescriptorProtos.UninterpretedOption element in UninterpretedOptionList) {
size += pb::CodedOutputStream.ComputeMessageSize(999, element);
}
@ -4230,6 +4283,15 @@ namespace Google.ProtocolBuffers.DescriptorProtos {
if (other.HasOptimizeFor) {
OptimizeFor = other.OptimizeFor;
}
if (other.HasCcGenericServices) {
CcGenericServices = other.CcGenericServices;
}
if (other.HasJavaGenericServices) {
JavaGenericServices = other.JavaGenericServices;
}
if (other.HasPyGenericServices) {
PyGenericServices = other.PyGenericServices;
}
if (other.uninterpretedOption_.Count != 0) {
base.AddRange(other.uninterpretedOption_, result.uninterpretedOption_);
}
@ -4290,6 +4352,18 @@ namespace Google.ProtocolBuffers.DescriptorProtos {
JavaMultipleFiles = input.ReadBool();
break;
}
case 128: {
CcGenericServices = input.ReadBool();
break;
}
case 136: {
JavaGenericServices = input.ReadBool();
break;
}
case 144: {
PyGenericServices = input.ReadBool();
break;
}
case 7994: {
global::Google.ProtocolBuffers.DescriptorProtos.UninterpretedOption.Builder subBuilder = global::Google.ProtocolBuffers.DescriptorProtos.UninterpretedOption.CreateBuilder();
input.ReadMessage(subBuilder, extensionRegistry);
@ -4375,6 +4449,60 @@ namespace Google.ProtocolBuffers.DescriptorProtos {
return this;
}
public bool HasCcGenericServices {
get { return result.HasCcGenericServices; }
}
public bool CcGenericServices {
get { return result.CcGenericServices; }
set { SetCcGenericServices(value); }
}
public Builder SetCcGenericServices(bool value) {
result.hasCcGenericServices = true;
result.ccGenericServices_ = value;
return this;
}
public Builder ClearCcGenericServices() {
result.hasCcGenericServices = false;
result.ccGenericServices_ = true;
return this;
}
public bool HasJavaGenericServices {
get { return result.HasJavaGenericServices; }
}
public bool JavaGenericServices {
get { return result.JavaGenericServices; }
set { SetJavaGenericServices(value); }
}
public Builder SetJavaGenericServices(bool value) {
result.hasJavaGenericServices = true;
result.javaGenericServices_ = value;
return this;
}
public Builder ClearJavaGenericServices() {
result.hasJavaGenericServices = false;
result.javaGenericServices_ = true;
return this;
}
public bool HasPyGenericServices {
get { return result.HasPyGenericServices; }
}
public bool PyGenericServices {
get { return result.PyGenericServices; }
set { SetPyGenericServices(value); }
}
public Builder SetPyGenericServices(bool value) {
result.hasPyGenericServices = true;
result.pyGenericServices_ = value;
return this;
}
public Builder ClearPyGenericServices() {
result.hasPyGenericServices = false;
result.pyGenericServices_ = true;
return this;
}
public pbc::IPopsicleList<global::Google.ProtocolBuffers.DescriptorProtos.UninterpretedOption> UninterpretedOptionList {
get { return result.uninterpretedOption_; }
}
@ -4450,6 +4578,16 @@ namespace Google.ProtocolBuffers.DescriptorProtos {
get { return messageSetWireFormat_; }
}
public const int NoStandardDescriptorAccessorFieldNumber = 2;
private bool hasNoStandardDescriptorAccessor;
private bool noStandardDescriptorAccessor_ = false;
public bool HasNoStandardDescriptorAccessor {
get { return hasNoStandardDescriptorAccessor; }
}
public bool NoStandardDescriptorAccessor {
get { return noStandardDescriptorAccessor_; }
}
public const int UninterpretedOptionFieldNumber = 999;
private pbc::PopsicleList<global::Google.ProtocolBuffers.DescriptorProtos.UninterpretedOption> uninterpretedOption_ = new pbc::PopsicleList<global::Google.ProtocolBuffers.DescriptorProtos.UninterpretedOption>();
public scg::IList<global::Google.ProtocolBuffers.DescriptorProtos.UninterpretedOption> UninterpretedOptionList {
@ -4478,6 +4616,9 @@ namespace Google.ProtocolBuffers.DescriptorProtos {
if (HasMessageSetWireFormat) {
output.WriteBool(1, MessageSetWireFormat);
}
if (HasNoStandardDescriptorAccessor) {
output.WriteBool(2, NoStandardDescriptorAccessor);
}
foreach (global::Google.ProtocolBuffers.DescriptorProtos.UninterpretedOption element in UninterpretedOptionList) {
output.WriteMessage(999, element);
}
@ -4495,6 +4636,9 @@ namespace Google.ProtocolBuffers.DescriptorProtos {
if (HasMessageSetWireFormat) {
size += pb::CodedOutputStream.ComputeBoolSize(1, MessageSetWireFormat);
}
if (HasNoStandardDescriptorAccessor) {
size += pb::CodedOutputStream.ComputeBoolSize(2, NoStandardDescriptorAccessor);
}
foreach (global::Google.ProtocolBuffers.DescriptorProtos.UninterpretedOption element in UninterpretedOptionList) {
size += pb::CodedOutputStream.ComputeMessageSize(999, element);
}
@ -4595,6 +4739,9 @@ namespace Google.ProtocolBuffers.DescriptorProtos {
if (other.HasMessageSetWireFormat) {
MessageSetWireFormat = other.MessageSetWireFormat;
}
if (other.HasNoStandardDescriptorAccessor) {
NoStandardDescriptorAccessor = other.NoStandardDescriptorAccessor;
}
if (other.uninterpretedOption_.Count != 0) {
base.AddRange(other.uninterpretedOption_, result.uninterpretedOption_);
}
@ -4635,6 +4782,10 @@ namespace Google.ProtocolBuffers.DescriptorProtos {
MessageSetWireFormat = input.ReadBool();
break;
}
case 16: {
NoStandardDescriptorAccessor = input.ReadBool();
break;
}
case 7994: {
global::Google.ProtocolBuffers.DescriptorProtos.UninterpretedOption.Builder subBuilder = global::Google.ProtocolBuffers.DescriptorProtos.UninterpretedOption.CreateBuilder();
input.ReadMessage(subBuilder, extensionRegistry);
@ -4664,6 +4815,24 @@ namespace Google.ProtocolBuffers.DescriptorProtos {
return this;
}
public bool HasNoStandardDescriptorAccessor {
get { return result.HasNoStandardDescriptorAccessor; }
}
public bool NoStandardDescriptorAccessor {
get { return result.NoStandardDescriptorAccessor; }
set { SetNoStandardDescriptorAccessor(value); }
}
public Builder SetNoStandardDescriptorAccessor(bool value) {
result.hasNoStandardDescriptorAccessor = true;
result.noStandardDescriptorAccessor_ = value;
return this;
}
public Builder ClearNoStandardDescriptorAccessor() {
result.hasNoStandardDescriptorAccessor = false;
result.noStandardDescriptorAccessor_ = false;
return this;
}
public pbc::IPopsicleList<global::Google.ProtocolBuffers.DescriptorProtos.UninterpretedOption> UninterpretedOptionList {
get { return result.uninterpretedOption_; }
}
@ -4732,6 +4901,7 @@ namespace Google.ProtocolBuffers.DescriptorProtos {
#region Nested types
public static class Types {
public enum CType {
STRING = 0,
CORD = 1,
STRING_PIECE = 2,
}
@ -4741,7 +4911,7 @@ namespace Google.ProtocolBuffers.DescriptorProtos {
public const int CtypeFieldNumber = 1;
private bool hasCtype;
private global::Google.ProtocolBuffers.DescriptorProtos.FieldOptions.Types.CType ctype_ = global::Google.ProtocolBuffers.DescriptorProtos.FieldOptions.Types.CType.CORD;
private global::Google.ProtocolBuffers.DescriptorProtos.FieldOptions.Types.CType ctype_ = global::Google.ProtocolBuffers.DescriptorProtos.FieldOptions.Types.CType.STRING;
public bool HasCtype {
get { return hasCtype; }
}
@ -5036,7 +5206,7 @@ namespace Google.ProtocolBuffers.DescriptorProtos {
}
public Builder ClearCtype() {
result.hasCtype = false;
result.ctype_ = global::Google.ProtocolBuffers.DescriptorProtos.FieldOptions.Types.CType.CORD;
result.ctype_ = global::Google.ProtocolBuffers.DescriptorProtos.FieldOptions.Types.CType.STRING;
return this;
}

@ -37,7 +37,7 @@ namespace Google.ProtocolBuffers.Descriptors {
/// <summary>
/// Descriptor for an enum type in a .proto file.
/// </summary>
public sealed class EnumDescriptor : IndexedDescriptorBase<EnumDescriptorProto, EnumOptions> {
public sealed class EnumDescriptor : IndexedDescriptorBase<EnumDescriptorProto, EnumOptions>, IEnumLiteMap<EnumValueDescriptor> {
private readonly MessageDescriptor containingType;
private readonly IList<EnumValueDescriptor> values;
@ -72,14 +72,24 @@ 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.
/// </summary>
internal EnumValueDescriptor FindValueByNumber(int number) {
public EnumValueDescriptor FindValueByNumber(int number) {
return File.DescriptorPool.FindEnumValueByNumber(this, number);
}
IEnumLite IEnumLiteMap.FindValueByNumber(int number) {
return FindValueByNumber(number);
}
/// <summary>
/// Finds an enum value by name.
/// </summary>

@ -36,7 +36,7 @@ namespace Google.ProtocolBuffers.Descriptors {
/// <summary>
/// Descriptor for a single enum value within an enum in a .proto file.
/// </summary>
public sealed class EnumValueDescriptor : IndexedDescriptorBase<EnumValueDescriptorProto, EnumValueOptions> {
public sealed class EnumValueDescriptor : IndexedDescriptorBase<EnumValueDescriptorProto, EnumValueOptions>, IEnumLite {
private readonly EnumDescriptor enumDescriptor;

@ -40,7 +40,7 @@ namespace Google.ProtocolBuffers.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> {
public sealed class FieldDescriptor : IndexedDescriptorBase<FieldDescriptorProto, FieldOptions>, IComparable<FieldDescriptor>, IFieldDescriptorLite {
private readonly MessageDescriptor extensionScope;
private EnumDescriptor enumType;
@ -299,9 +299,26 @@ 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>
public EnumDescriptor EnumType {

@ -30,6 +30,8 @@
// (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.Generic;
using Google.ProtocolBuffers.Collections;
namespace Google.ProtocolBuffers.Descriptors {
@ -46,5 +48,29 @@ namespace Google.ProtocolBuffers.Descriptors {
internal MappedType MappedType { get; private set; }
internal WireFormat.WireType WireType { get; private set; }
/// <summary>
/// Immutable mapping from field type to mapped type. Built using the attributes on
/// FieldType values.
/// </summary>
static readonly IDictionary<FieldType, FieldMappingAttribute> FieldTypeToMappedTypeMap = MapFieldTypes();
private static IDictionary<FieldType, FieldMappingAttribute> MapFieldTypes() {
var map = new Dictionary<FieldType, FieldMappingAttribute>();
foreach (System.Reflection.FieldInfo field in typeof(FieldType).GetFields(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public)) {
FieldType fieldType = (FieldType)field.GetValue(null);
FieldMappingAttribute mapping = (FieldMappingAttribute)field.GetCustomAttributes(typeof(FieldMappingAttribute), false)[0];
map[fieldType] = mapping;
}
return Dictionaries.AsReadOnly(map);
}
internal static MappedType MappedTypeFromFieldType(FieldType type) {
return FieldTypeToMappedTypeMap[type].MappedType;
}
internal static WireFormat.WireType WireTypeFromFieldType(FieldType type, bool packed) {
return packed ? WireFormat.WireType.LengthDelimited : FieldTypeToMappedTypeMap[type].WireType;
}
}
}

@ -180,7 +180,7 @@ namespace Google.ProtocolBuffers {
}
public override IDictionary<FieldDescriptor, object> AllFields {
get { return fields.AllFields; }
get { return fields.AllFieldDescriptors; }
}
public override bool HasField(FieldDescriptor field) {
@ -216,7 +216,7 @@ namespace Google.ProtocolBuffers {
}
public bool Initialized {
get { return fields.IsInitializedWithRespectTo(type); }
get { return fields.IsInitializedWithRespectTo(type.Fields); }
}
public override void WriteTo(CodedOutputStream output) {
@ -295,7 +295,8 @@ namespace Google.ProtocolBuffers {
}
public override Builder MergeFrom(DynamicMessage other) {
return MergeFrom((IMessage)other);
IMessage downcast = other;
return MergeFrom(downcast);
}
public override DynamicMessage Build() {
@ -335,7 +336,7 @@ namespace Google.ProtocolBuffers {
}
public override bool IsInitialized {
get { return fields.IsInitializedWithRespectTo(type); }
get { return fields.IsInitializedWithRespectTo(type.Fields); }
}
public override Builder MergeFrom(CodedInputStream input, ExtensionRegistry extensionRegistry) {
@ -354,7 +355,7 @@ namespace Google.ProtocolBuffers {
}
public override IDictionary<FieldDescriptor, object> AllFields {
get { return fields.AllFields; }
get { return fields.AllFieldDescriptors; }
}
public override IBuilder CreateBuilderForField(FieldDescriptor field) {

@ -0,0 +1,106 @@
#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.Globalization;
using System.Text;
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);
}
public class EnumLiteMap<TEnum> : IEnumLiteMap<IEnumLite>
where TEnum : struct, IComparable, IFormattable {
struct EnumValue : IEnumLite {
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(); }
}
}
private readonly SortedList<int, IEnumLite> items;
public EnumLiteMap() {
items = new SortedList<int, IEnumLite>();
foreach (TEnum evalue in Enum.GetValues(typeof(TEnum)))
items.Add(Convert.ToInt32(evalue), new EnumValue(evalue));
}
IEnumLite IEnumLiteMap.FindValueByNumber(int number) {
return FindValueByNumber(number);
}
public IEnumLite FindValueByNumber(int number) {
IEnumLite val;
return items.TryGetValue(number, out val) ? val : null;
}
public bool IsValidValue(IEnumLite value) {
return items.ContainsKey(value.Number);
}
}
}

@ -94,21 +94,21 @@ namespace Google.ProtocolBuffers {
/// <summary>
/// Appends a value to a repeated extension.
/// </summary>
public ExtendableBuilder<TMessage, TBuilder> AddExtension<TExtension>(GeneratedExtensionBase<IList<TExtension>> extension, TExtension value) {
public TBuilder AddExtension<TExtension>(GeneratedExtensionBase<IList<TExtension>> extension, TExtension value) {
ExtendableMessage<TMessage, TBuilder> message = MessageBeingBuilt;
message.VerifyExtensionContainingType(extension);
message.Extensions.AddRepeatedField(extension.Descriptor, extension.SingularToReflectionType(value));
return this;
return ThisBuilder;
}
/// <summary>
/// Clears an extension.
/// </summary>
public ExtendableBuilder<TMessage, TBuilder> ClearExtension<TExtension>(GeneratedExtensionBase<TExtension> extension) {
public TBuilder ClearExtension<TExtension>(GeneratedExtensionBase<TExtension> extension) {
ExtendableMessage<TMessage, TBuilder> message = MessageBeingBuilt;
message.VerifyExtensionContainingType(extension);
message.Extensions.ClearField(extension.Descriptor);
return this;
return ThisBuilder;
}
/// <summary>

@ -0,0 +1,262 @@
#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;
namespace Google.ProtocolBuffers {
public abstract class ExtendableBuilderLite<TMessage, TBuilder> : GeneratedBuilderLite<TMessage, TBuilder>
where TMessage : ExtendableMessageLite<TMessage, TBuilder>
where TBuilder : GeneratedBuilderLite<TMessage, TBuilder> {
protected ExtendableBuilderLite() { }
/// <summary>
/// Checks if a singular extension is present
/// </summary>
public bool HasExtension<TExtension>(GeneratedExtensionLite<TMessage, TExtension> extension) {
return MessageBeingBuilt.HasExtension(extension);
}
/// <summary>
/// Returns the number of elements in a repeated extension.
/// </summary>
public int GetExtensionCount<TExtension>(GeneratedExtensionLite<TMessage, IList<TExtension>> extension) {
return MessageBeingBuilt.GetExtensionCount(extension);
}
/// <summary>
/// Returns the value of an extension.
/// </summary>
public TExtension GetExtension<TExtension>(GeneratedExtensionLite<TMessage, TExtension> extension) {
return MessageBeingBuilt.GetExtension(extension);
}
/// <summary>
/// Returns one element of a repeated extension.
/// </summary>
public TExtension GetExtension<TExtension>(GeneratedExtensionLite<TMessage, IList<TExtension>> extension, int index) {
return MessageBeingBuilt.GetExtension(extension, index);
}
/// <summary>
/// Sets the value of an extension.
/// </summary>
public TBuilder SetExtension<TExtension>(GeneratedExtensionLite<TMessage, TExtension> extension, TExtension value) {
ExtendableMessageLite<TMessage, TBuilder> message = MessageBeingBuilt;
message.VerifyExtensionContainingType(extension);
message.Extensions[extension.Descriptor] = extension.ToReflectionType(value);
return ThisBuilder;
}
/// <summary>
/// Sets the value of one element of a repeated extension.
/// </summary>
public TBuilder SetExtension<TExtension>(GeneratedExtensionLite<TMessage, IList<TExtension>> extension, int index, TExtension value) {
ExtendableMessageLite<TMessage, TBuilder> message = MessageBeingBuilt;
message.VerifyExtensionContainingType(extension);
message.Extensions[extension.Descriptor, index] = extension.SingularToReflectionType(value);
return ThisBuilder;
}
/// <summary>
/// Appends a value to a repeated extension.
/// </summary>
public TBuilder AddExtension<TExtension>(GeneratedExtensionLite<TMessage, IList<TExtension>> extension, TExtension value) {
ExtendableMessageLite<TMessage, TBuilder> message = MessageBeingBuilt;
message.VerifyExtensionContainingType(extension);
message.Extensions.AddRepeatedField(extension.Descriptor, extension.SingularToReflectionType(value));
return ThisBuilder;
}
/// <summary>
/// Clears an extension.
/// </summary>
public TBuilder ClearExtension<TExtension>(GeneratedExtensionLite<TMessage, TExtension> extension) {
ExtendableMessageLite<TMessage, TBuilder> message = MessageBeingBuilt;
message.VerifyExtensionContainingType(extension);
message.Extensions.ClearField(extension.Descriptor);
return ThisBuilder;
}
/// <summary>
/// Called by subclasses to parse an unknown field or an extension.
/// </summary>
/// <returns>true unless the tag is an end-group tag</returns>
[CLSCompliant(false)]
protected override bool ParseUnknownField(CodedInputStream input,
ExtensionRegistry extensionRegistry, uint tag) {
FieldSet extensions = MessageBeingBuilt.Extensions;
WireFormat.WireType wireType = WireFormat.GetTagWireType(tag);
int fieldNumber = WireFormat.GetTagFieldNumber(tag);
IGeneratedExtensionLite extension = extensionRegistry[DefaultInstanceForType, fieldNumber];
bool unknown = false;
bool packed = false;
if (extension == null) {
unknown = true; // Unknown field.
} else if (wireType == FieldMappingAttribute.WireTypeFromFieldType(extension.Descriptor.FieldType, false /* isPacked */)) {
packed = false; // Normal, unpacked value.
} else if (extension.Descriptor.IsRepeated &&
//?? just returns true ?? extension.Descriptor.type.isPackable() &&
wireType == FieldMappingAttribute.WireTypeFromFieldType(extension.Descriptor.FieldType, true /* isPacked */)) {
packed = true; // Packed value.
} else {
unknown = true; // Wrong wire type.
}
if (unknown) { // Unknown field or wrong wire type. Skip.
return input.SkipField(tag);
}
if (packed) {
int length = (int)Math.Min(int.MaxValue, input.ReadRawVarint32());
int limit = input.PushLimit(length);
if (extension.Descriptor.FieldType == FieldType.Enum) {
while (!input.ReachedLimit) {
int rawValue = input.ReadEnum();
Object value =
extension.Descriptor.EnumType.FindValueByNumber(rawValue);
if (value == null) {
// If the number isn't recognized as a valid value for this
// enum, drop it (don't even add it to unknownFields).
return true;
}
extensions.AddRepeatedField(extension.Descriptor, value);
}
} else {
while (!input.ReachedLimit) {
Object value = input.ReadPrimitiveField(extension.Descriptor.FieldType);
extensions.AddRepeatedField(extension.Descriptor, value);
}
}
input.PopLimit(limit);
} else {
Object value;
switch (extension.Descriptor.MappedType) {
case MappedType.Message: {
IBuilderLite subBuilder = null;
if (!extension.Descriptor.IsRepeated) {
IMessageLite existingValue = extensions[extension.Descriptor] as IMessageLite;
if (existingValue != null) {
subBuilder = existingValue.WeakToBuilder();
}
}
if (subBuilder == null) {
subBuilder = extension.MessageDefaultInstance.WeakCreateBuilderForType();
}
if (extension.Descriptor.FieldType == FieldType.Group) {
input.ReadGroup(extension.Number, subBuilder, extensionRegistry);
} else {
input.ReadMessage(subBuilder, extensionRegistry);
}
value = subBuilder.WeakBuild();
break;
}
case MappedType.Enum:
int rawValue = input.ReadEnum();
value = extension.Descriptor.EnumType.FindValueByNumber(rawValue);
// If the number isn't recognized as a valid value for this enum,
// drop it.
if (value == null) {
return true;
}
break;
default:
value = input.ReadPrimitiveField(extension.Descriptor.FieldType);
break;
}
if (extension.Descriptor.IsRepeated) {
extensions.AddRepeatedField(extension.Descriptor, value);
} else {
extensions[extension.Descriptor] = value;
}
}
return true;
}
#region Reflection
public object this[IFieldDescriptorLite field, int index] {
set {
if (field.IsExtension) {
ExtendableMessageLite<TMessage, TBuilder> message = MessageBeingBuilt;
message.Extensions[field, index] = value;
} else {
throw new NotSupportedException("Not supported in the lite runtime.");
}
}
}
public object this[IFieldDescriptorLite field] {
set {
if (field.IsExtension) {
ExtendableMessageLite<TMessage, TBuilder> message = MessageBeingBuilt;
message.Extensions[field] = value;
} else {
throw new NotSupportedException("Not supported in the lite runtime.");
}
}
}
public TBuilder ClearField(IFieldDescriptorLite field) {
if (field.IsExtension) {
ExtendableMessageLite<TMessage, TBuilder> message = MessageBeingBuilt;
message.Extensions.ClearField(field);
return ThisBuilder;
} else {
throw new NotSupportedException("Not supported in the lite runtime.");
}
}
public TBuilder AddRepeatedField(IFieldDescriptorLite field, object value) {
if (field.IsExtension) {
ExtendableMessageLite<TMessage, TBuilder> message = MessageBeingBuilt;
message.Extensions.AddRepeatedField(field, value);
return ThisBuilder;
} else {
throw new NotSupportedException("Not supported in the lite runtime.");
}
}
protected void MergeExtensionFields(ExtendableMessageLite<TMessage, TBuilder> other) {
MessageBeingBuilt.Extensions.MergeFrom(other.Extensions);
}
#endregion
}
}

@ -102,8 +102,8 @@ namespace Google.ProtocolBuffers {
public override IDictionary<FieldDescriptor, object> AllFields {
get {
IDictionary<FieldDescriptor, object> result = GetMutableFieldMap();
foreach(KeyValuePair<FieldDescriptor, object> entry in extensions.AllFields) {
result[entry.Key] = entry.Value;
foreach(KeyValuePair<IFieldDescriptorLite, object> entry in extensions.AllFields) {
result[(FieldDescriptor)entry.Key] = entry.Value;
}
return Dictionaries.AsReadOnly(result);
}
@ -173,9 +173,9 @@ namespace Google.ProtocolBuffers {
/// TODO(jonskeet): See if we can improve this in terms of readability.
/// </summary>
protected class ExtensionWriter {
readonly IEnumerator<KeyValuePair<FieldDescriptor, object>> iterator;
readonly IEnumerator<KeyValuePair<IFieldDescriptorLite, object>> iterator;
readonly FieldSet extensions;
KeyValuePair<FieldDescriptor, object>? next = null;
KeyValuePair<IFieldDescriptorLite, object>? next = null;
internal ExtensionWriter(ExtendableMessage<TMessage, TBuilder> message) {
extensions = message.extensions;

@ -0,0 +1,184 @@
#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.Collections;
namespace Google.ProtocolBuffers {
public abstract class ExtendableMessageLite<TMessage, TBuilder> : GeneratedMessageLite<TMessage, TBuilder>
where TMessage : GeneratedMessageLite<TMessage, TBuilder>
where TBuilder : GeneratedBuilderLite<TMessage, TBuilder> {
protected ExtendableMessageLite() { }
private readonly FieldSet extensions = FieldSet.CreateInstance();
/// <summary>
/// Access for the builder.
/// </summary>
internal FieldSet Extensions {
get { return extensions; }
}
public override bool Equals(object obj) {
ExtendableMessageLite<TMessage, TBuilder> other = obj as ExtendableMessageLite<TMessage, TBuilder>;
return !ReferenceEquals(null, other) &&
Dictionaries.Equals(extensions.AllFields, other.extensions.AllFields);
}
public override int GetHashCode() {
return Dictionaries.GetHashCode(extensions.AllFields);
}
/// <summary>
/// writes the extensions to the text stream
/// </summary>
public override void PrintTo(System.IO.TextWriter writer) {
foreach (KeyValuePair<IFieldDescriptorLite, object> entry in extensions.AllFields) {
string fn = string.Format("[{0}]", entry.Key.FullName);
if (entry.Key.IsRepeated) {
foreach (object o in ((IEnumerable)entry.Value))
PrintField(fn, true, o, writer);
} else {
PrintField(fn, true, entry.Value, writer);
}
}
}
/// <summary>
/// Checks if a singular extension is present.
/// </summary>
public bool HasExtension<TExtension>(GeneratedExtensionLite<TMessage, TExtension> extension) {
VerifyExtensionContainingType(extension);
return extensions.HasField(extension.Descriptor);
}
/// <summary>
/// Returns the number of elements in a repeated extension.
/// </summary>
public int GetExtensionCount<TExtension>(GeneratedExtensionLite<TMessage, IList<TExtension>> extension) {
VerifyExtensionContainingType(extension);
return extensions.GetRepeatedFieldCount(extension.Descriptor);
}
/// <summary>
/// Returns the value of an extension.
/// </summary>
public TExtension GetExtension<TExtension>(GeneratedExtensionLite<TMessage, TExtension> extension) {
VerifyExtensionContainingType(extension);
object value = extensions[extension.Descriptor];
if (value == null) {
return extension.DefaultValue;
} else {
return (TExtension)extension.FromReflectionType(value);
}
}
/// <summary>
/// Returns one element of a repeated extension.
/// </summary>
public TExtension GetExtension<TExtension>(GeneratedExtensionLite<TMessage, IList<TExtension>> extension, int index) {
VerifyExtensionContainingType(extension);
return (TExtension)extension.SingularFromReflectionType(extensions[extension.Descriptor, index]);
}
/// <summary>
/// Called to check if all extensions are initialized.
/// </summary>
protected bool ExtensionsAreInitialized {
get { return extensions.IsInitialized; }
}
public override bool IsInitialized {
get {
return ExtensionsAreInitialized;
}
}
/// <summary>
/// Used by subclasses to serialize extensions. Extension ranges may be
/// interleaves with field numbers, but we must write them in canonical
/// (sorted by field number) order. This class helps us to write individual
/// ranges of extensions at once.
///
/// TODO(jonskeet): See if we can improve this in terms of readability.
/// </summary>
protected class ExtensionWriter {
readonly IEnumerator<KeyValuePair<IFieldDescriptorLite, object>> iterator;
readonly FieldSet extensions;
KeyValuePair<IFieldDescriptorLite, object>? next = null;
internal ExtensionWriter(ExtendableMessageLite<TMessage, TBuilder> message) {
extensions = message.extensions;
iterator = message.extensions.GetEnumerator();
if (iterator.MoveNext()) {
next = iterator.Current;
}
}
public void WriteUntil(int end, CodedOutputStream output) {
while (next != null && next.Value.Key.FieldNumber < end) {
extensions.WriteField(next.Value.Key, next.Value.Value, output);
if (iterator.MoveNext()) {
next = iterator.Current;
} else {
next = null;
}
}
}
}
protected ExtensionWriter CreateExtensionWriter(ExtendableMessageLite<TMessage, TBuilder> message) {
return new ExtensionWriter(message);
}
/// <summary>
/// Called by subclasses to compute the size of extensions.
/// </summary>
protected int ExtensionsSerializedSize {
get { return extensions.SerializedSize; }
}
internal void VerifyExtensionContainingType<TExtension>(GeneratedExtensionLite<TMessage, TExtension> extension) {
if (!ReferenceEquals(extension.ContainingTypeDefaultInstance, DefaultInstanceForType)) {
// This can only happen if someone uses unchecked operations.
throw new ArgumentException(
String.Format("Extension is for type \"{0}\" which does not match message type \"{1}\".",
extension.ContainingTypeDefaultInstance, DefaultInstanceForType
));
}
}
}
}

@ -36,24 +36,42 @@ using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers
{
public sealed class ExtensionInfo {
public sealed class ExtensionInfo : IGeneratedExtensionLite {
/// <summary>
/// The extension's descriptor
/// </summary>
public FieldDescriptor Descriptor { get; private set; }
/// <summary>
IFieldDescriptorLite IGeneratedExtensionLite.Descriptor { get { return Descriptor; } }
/// <summary>
/// A default instance of the extensions's type, if it has a message type,
/// or null otherwise.
/// </summary>
public IMessage DefaultInstance { get; private set; }
public IMessageLite DefaultInstance { get; private set; }
internal ExtensionInfo(FieldDescriptor descriptor) : this(descriptor, null) {
}
internal ExtensionInfo(FieldDescriptor descriptor, IMessage defaultInstance) {
internal ExtensionInfo(FieldDescriptor descriptor, IMessageLite defaultInstance) {
Descriptor = descriptor;
DefaultInstance = defaultInstance;
}
#region IGeneratedExtensionLite Members
int IGeneratedExtensionLite.Number {
get { return Descriptor.FieldNumber; }
}
object IGeneratedExtensionLite.ContainingType {
get { return Descriptor; }
}
IMessageLite IGeneratedExtensionLite.MessageDefaultInstance {
get { return DefaultInstance; }
}
#endregion
}
}

@ -88,23 +88,20 @@ namespace Google.ProtocolBuffers {
/// could take advantage of this to inject a mutable object into a message
/// belonging to privileged code and create mischief.</para>
/// </remarks>
public sealed class ExtensionRegistry {
public sealed partial class ExtensionRegistry {
#if !LITE
private static readonly ExtensionRegistry empty = new ExtensionRegistry(
new Dictionary<string, ExtensionInfo>(),
new Dictionary<DescriptorIntPair, ExtensionInfo>(),
new Dictionary<ExtensionIntPair, IGeneratedExtensionLite>(),
true);
private readonly IDictionary<string, ExtensionInfo> extensionsByName;
private readonly IDictionary<DescriptorIntPair, ExtensionInfo> extensionsByNumber;
private readonly bool readOnly;
private ExtensionRegistry(IDictionary<String, ExtensionInfo> extensionsByName,
IDictionary<DescriptorIntPair, ExtensionInfo> extensionsByNumber,
bool readOnly) {
IDictionary<ExtensionIntPair, IGeneratedExtensionLite> extensionsByNumber,
bool readOnly)
: this(extensionsByNumber, readOnly) {
this.extensionsByName = extensionsByName;
this.extensionsByNumber = extensionsByNumber;
this.readOnly = readOnly;
}
/// <summary>
@ -112,19 +109,13 @@ namespace Google.ProtocolBuffers {
/// </summary>
public static ExtensionRegistry CreateInstance() {
return new ExtensionRegistry(new Dictionary<string, ExtensionInfo>(),
new Dictionary<DescriptorIntPair, ExtensionInfo>(), false);
}
/// <summary>
/// Get the unmodifiable singleton empty instance.
/// </summary>
public static ExtensionRegistry Empty {
get { return empty; }
new Dictionary<ExtensionIntPair, IGeneratedExtensionLite>(), false);
}
public ExtensionRegistry AsReadOnly() {
return new ExtensionRegistry(extensionsByName, extensionsByNumber, true);
}
#endif
/// <summary>
/// Finds an extension by fully-qualified field name, in the
@ -146,9 +137,9 @@ namespace Google.ProtocolBuffers {
/// </summary>
public ExtensionInfo this[MessageDescriptor containingType, int fieldNumber] {
get {
ExtensionInfo ret;
extensionsByNumber.TryGetValue(new DescriptorIntPair(containingType, fieldNumber), out ret);
return ret;
IGeneratedExtensionLite ret;
extensionsByNumber.TryGetValue(new ExtensionIntPair(containingType, fieldNumber), out ret);
return ret as ExtensionInfo;
}
}
@ -198,7 +189,7 @@ namespace Google.ProtocolBuffers {
}
extensionsByName[extension.Descriptor.FullName] = extension;
extensionsByNumber[new DescriptorIntPair(extension.Descriptor.ContainingType,
extensionsByNumber[new ExtensionIntPair(extension.Descriptor.ContainingType,
extension.Descriptor.FieldNumber)] = extension;
FieldDescriptor field = extension.Descriptor;
@ -212,34 +203,5 @@ namespace Google.ProtocolBuffers {
extensionsByName[field.MessageType.FullName] = extension;
}
}
/// <summary>
/// Nested type just used to represent a pair of MessageDescriptor and int, as
/// the key into the "by number" map.
/// </summary>
private struct DescriptorIntPair : IEquatable<DescriptorIntPair> {
readonly MessageDescriptor descriptor;
readonly int number;
internal DescriptorIntPair(MessageDescriptor descriptor, int number) {
this.descriptor = descriptor;
this.number = number;
}
public override int GetHashCode() {
return descriptor.GetHashCode() * ((1 << 16) - 1) + number;
}
public override bool Equals(object obj) {
if (!(obj is DescriptorIntPair)) {
return false;
}
return Equals((DescriptorIntPair)obj);
}
public bool Equals(DescriptorIntPair other) {
return descriptor == other.descriptor && number == other.number;
}
}
}
}

@ -0,0 +1,179 @@
#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;
namespace Google.ProtocolBuffers {
/// <summary>
/// A table of known extensions, searchable by name or field number. When
/// parsing a protocol message that might have extensions, you must provide
/// an <see cref="ExtensionRegistry"/> in which you have registered any extensions
/// that you want to be able to parse. Otherwise, those extensions will just
/// be treated like unknown fields.
/// </summary>
/// <example>
/// For example, if you had the <c>.proto</c> file:
/// <code>
/// option java_class = "MyProto";
///
/// message Foo {
/// extensions 1000 to max;
/// }
///
/// extend Foo {
/// optional int32 bar;
/// }
/// </code>
///
/// Then you might write code like:
///
/// <code>
/// extensionRegistry registry = extensionRegistry.CreateInstance();
/// registry.Add(MyProto.Bar);
/// MyProto.Foo message = MyProto.Foo.ParseFrom(input, registry);
/// </code>
/// </example>
///
/// <remarks>
/// <para>You might wonder why this is necessary. Two alternatives might come to
/// mind. First, you might imagine a system where generated extensions are
/// automatically registered when their containing classes are loaded. This
/// is a popular technique, but is bad design; among other things, it creates a
/// situation where behavior can change depending on what classes happen to be
/// loaded. It also introduces a security vulnerability, because an
/// unprivileged class could cause its code to be called unexpectedly from a
/// privileged class by registering itself as an extension of the right type.
/// </para>
/// <para>Another option you might consider is lazy parsing: do not parse an
/// extension until it is first requested, at which point the caller must
/// provide a type to use. This introduces a different set of problems. First,
/// it would require a mutex lock any time an extension was accessed, which
/// would be slow. Second, corrupt data would not be detected until first
/// access, at which point it would be much harder to deal with it. Third, it
/// could violate the expectation that message objects are immutable, since the
/// type provided could be any arbitrary message class. An unprivileged user
/// could take advantage of this to inject a mutable object into a message
/// belonging to privileged code and create mischief.</para>
/// </remarks>
public sealed partial class ExtensionRegistry {
private readonly IDictionary<ExtensionIntPair, IGeneratedExtensionLite> extensionsByNumber;
private readonly bool readOnly;
private ExtensionRegistry(IDictionary<ExtensionIntPair, IGeneratedExtensionLite> extensionsByNumber,
bool readOnly) {
this.extensionsByNumber = extensionsByNumber;
this.readOnly = readOnly;
}
#if LITE
private static readonly ExtensionRegistry empty = new ExtensionRegistry(
new Dictionary<ExtensionIntPair, IGeneratedExtensionLite>(),
true);
/// <summary>
/// Construct a new, empty instance.
/// </summary>
public static ExtensionRegistry CreateInstance() {
return new ExtensionRegistry(
new Dictionary<ExtensionIntPair, IGeneratedExtensionLite>(), false);
}
public ExtensionRegistry AsReadOnly() {
return new ExtensionRegistry(extensionsByNumber, true);
}
#endif
/// <summary>
/// Get the unmodifiable singleton empty instance.
/// </summary>
public static ExtensionRegistry Empty {
get { return empty; }
}
/// <summary>
/// Finds an extension by containing type and field number.
/// A null reference is returned if the extension can't be found.
/// </summary>
public IGeneratedExtensionLite this[IMessageLite containingType, int fieldNumber] {
get {
IGeneratedExtensionLite ret;
extensionsByNumber.TryGetValue(new ExtensionIntPair(containingType, fieldNumber), out ret);
return ret;
}
}
/// <summary>
/// Add an extension from a generated file to the registry.
/// </summary>
public void Add(IGeneratedExtensionLite extension) {
if (readOnly) {
throw new InvalidOperationException("Cannot add entries to a read-only extension registry");
}
extensionsByNumber.Add(
new ExtensionIntPair(extension.ContainingType, extension.Number),
extension);
}
/// <summary>
/// Nested type just used to represent a pair of MessageDescriptor and int, as
/// the key into the "by number" map.
/// </summary>
private struct ExtensionIntPair : IEquatable<ExtensionIntPair> {
readonly object msgType;
readonly int number;
internal ExtensionIntPair(object msgType, int number) {
this.msgType = msgType;
this.number = number;
}
public override int GetHashCode() {
return msgType.GetHashCode() * ((1 << 16) - 1) + number;
}
public override bool Equals(object obj) {
if (!(obj is ExtensionIntPair)) {
return false;
}
return Equals((ExtensionIntPair)obj);
}
public bool Equals(ExtensionIntPair other) {
return msgType.Equals(other.msgType) && number == other.number;
}
}
}
}

@ -71,7 +71,7 @@ namespace Google.ProtocolBuffers.FieldAccess {
}
// No... so let's create a builder of the right type, and merge the value in.
IMessage message = (IMessage) value;
IMessageLite message = (IMessageLite) value;
return CreateBuilder().WeakMergeFrom(message).WeakBuild();
}

@ -67,7 +67,7 @@ namespace Google.ProtocolBuffers.FieldAccess {
}
// No... so let's create a builder of the right type, and merge the value in.
IMessage message = (IMessage) value;
IMessageLite message = (IMessageLite) value;
return CreateBuilder().WeakMergeFrom(message).WeakBuild();
}

@ -39,6 +39,21 @@ using Google.ProtocolBuffers.Collections;
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers {
public interface IFieldDescriptorLite : IComparable<IFieldDescriptorLite> {
bool IsRepeated { get; }
bool IsRequired { get; }
bool IsPacked { get; }
bool IsExtension { get; }
bool MessageSetWireFormat { get; } //field.ContainingType.Options.MessageSetWireFormat
int FieldNumber { get; }
string FullName { get; }
IEnumLiteMap EnumType { get; }
FieldType FieldType { get; }
MappedType MappedType { get; }
object DefaultValue { get; }
}
/// <summary>
/// A class which represents an arbitrary set of fields of some message type.
/// This is used to implement DynamicMessage, and also to represent extensions
@ -56,17 +71,17 @@ namespace Google.ProtocolBuffers {
/// </summary>
internal sealed class FieldSet {
private static readonly FieldSet defaultInstance = new FieldSet(new Dictionary<FieldDescriptor, object>()).MakeImmutable();
private static readonly FieldSet defaultInstance = new FieldSet(new Dictionary<IFieldDescriptorLite, object>()).MakeImmutable();
private IDictionary<FieldDescriptor, object> fields;
private IDictionary<IFieldDescriptorLite, object> fields;
private FieldSet(IDictionary<FieldDescriptor, object> fields) {
private FieldSet(IDictionary<IFieldDescriptorLite, object> fields) {
this.fields = fields;
}
public static FieldSet CreateInstance() {
// Use SortedList to keep fields in the canonical order
return new FieldSet(new SortedList<FieldDescriptor, object>());
return new FieldSet(new SortedList<IFieldDescriptorLite, object>());
}
/// <summary>
@ -85,8 +100,8 @@ namespace Google.ProtocolBuffers {
}
if (hasRepeats) {
var tmp = new SortedList<FieldDescriptor, object>();
foreach (KeyValuePair<FieldDescriptor, object> entry in fields) {
var tmp = new SortedList<IFieldDescriptorLite, object>();
foreach (KeyValuePair<IFieldDescriptorLite, object> entry in fields) {
IList<object> list = entry.Value as IList<object>;
tmp[entry.Key] = list == null ? entry.Value : Lists.AsReadOnly(list);
}
@ -110,14 +125,26 @@ namespace Google.ProtocolBuffers {
/// is immutable, the entries may not be (i.e. any repeated values are represented by
/// mutable lists). The behaviour is not specified if the contents are mutated.
/// </summary>
internal IDictionary<FieldDescriptor, object> AllFields {
internal IDictionary<IFieldDescriptorLite, object> AllFields {
get { return Dictionaries.AsReadOnly(fields); }
}
#if !LITE
/// <summary>
/// Force coercion to full descriptor dictionary.
/// </summary>
internal IDictionary<Descriptors.FieldDescriptor, object> AllFieldDescriptors {
get {
SortedList<Descriptors.FieldDescriptor, object> copy = new SortedList<Google.ProtocolBuffers.Descriptors.FieldDescriptor, object>();
foreach (KeyValuePair<IFieldDescriptorLite, object> fd in fields)
copy.Add((Descriptors.FieldDescriptor)fd.Key, fd.Value);
return Dictionaries.AsReadOnly(copy);
}
}
#endif
/// <summary>
/// See <see cref="IMessage.HasField"/>.
/// See <see cref="IMessageLite.HasField"/>.
/// </summary>
public bool HasField(FieldDescriptor field) {
public bool HasField(IFieldDescriptorLite field) {
if (field.IsRepeated) {
throw new ArgumentException("HasField() can only be called on non-repeated fields.");
}
@ -133,7 +160,7 @@ namespace Google.ProtocolBuffers {
}
/// <summary>
/// See <see cref="IMessage.Item(FieldDescriptor)"/>
/// See <see cref="IMessageLite.Item(IFieldDescriptorLite)"/>
/// </summary>
/// <remarks>
/// If the field is not set, the behaviour when fetching this property varies by field type:
@ -153,7 +180,7 @@ namespace Google.ProtocolBuffers {
/// to ensure it is of an appropriate type.
/// </remarks>
///
internal object this[FieldDescriptor field] {
internal object this[IFieldDescriptorLite field] {
get {
object result;
if (fields.TryGetValue(field, out result)) {
@ -191,9 +218,9 @@ namespace Google.ProtocolBuffers {
}
/// <summary>
/// See <see cref="IMessage.Item(FieldDescriptor,int)" />
/// See <see cref="IMessageLite.Item(IFieldDescriptorLite,int)" />
/// </summary>
internal object this[FieldDescriptor field, int index] {
internal object this[IFieldDescriptorLite field, int index] {
get {
if (!field.IsRepeated) {
throw new ArgumentException("Indexer specifying field and index can only be called on repeated fields.");
@ -217,7 +244,7 @@ namespace Google.ProtocolBuffers {
/// <summary>
/// See <see cref="IBuilder{TMessage, TBuilder}.AddRepeatedField" />
/// </summary>
internal void AddRepeatedField(FieldDescriptor field, object value) {
internal void AddRepeatedField(IFieldDescriptorLite field, object value) {
if (!field.IsRepeated) {
throw new ArgumentException("AddRepeatedField can only be called on repeated fields.");
}
@ -233,12 +260,12 @@ namespace Google.ProtocolBuffers {
/// <summary>
/// Returns an enumerator for the field map. Used to write the fields out.
/// </summary>
internal IEnumerator<KeyValuePair<FieldDescriptor, object>> GetEnumerator() {
internal IEnumerator<KeyValuePair<IFieldDescriptorLite, object>> GetEnumerator() {
return fields.GetEnumerator();
}
/// <summary>
/// See <see cref="IMessage.IsInitialized" />
/// See <see cref="IMessageLite.IsInitialized" />
/// </summary>
/// <remarks>
/// Since FieldSet itself does not have any way of knowing about
@ -248,17 +275,17 @@ namespace Google.ProtocolBuffers {
/// </remarks>
internal bool IsInitialized {
get {
foreach (KeyValuePair<FieldDescriptor, object> entry in fields) {
FieldDescriptor field = entry.Key;
foreach (KeyValuePair<IFieldDescriptorLite, object> entry in fields) {
IFieldDescriptorLite field = entry.Key;
if (field.MappedType == MappedType.Message) {
if (field.IsRepeated) {
foreach(IMessage message in (IEnumerable) entry.Value) {
foreach(IMessageLite message in (IEnumerable) entry.Value) {
if (!message.IsInitialized) {
return false;
}
}
} else {
if (!((IMessage) entry.Value).IsInitialized) {
if (!((IMessageLite)entry.Value).IsInitialized) {
return false;
}
}
@ -273,8 +300,8 @@ namespace Google.ProtocolBuffers {
/// descriptor are present in this field set, as well as whether
/// all the embedded messages are themselves initialized.
/// </summary>
internal bool IsInitializedWithRespectTo(MessageDescriptor type) {
foreach (FieldDescriptor field in type.Fields) {
internal bool IsInitializedWithRespectTo(IEnumerable typeFields) {
foreach (IFieldDescriptorLite field in typeFields) {
if (field.IsRequired && !HasField(field)) {
return false;
}
@ -285,14 +312,14 @@ namespace Google.ProtocolBuffers {
/// <summary>
/// See <see cref="IBuilder{TMessage, TBuilder}.ClearField" />
/// </summary>
public void ClearField(FieldDescriptor field) {
public void ClearField(IFieldDescriptorLite field) {
fields.Remove(field);
}
/// <summary>
/// See <see cref="IMessage.GetRepeatedFieldCount" />
/// See <see cref="IMessageLite.GetRepeatedFieldCount" />
/// </summary>
public int GetRepeatedFieldCount(FieldDescriptor field) {
public int GetRepeatedFieldCount(IFieldDescriptorLite field) {
if (!field.IsRepeated) {
throw new ArgumentException("GetRepeatedFieldCount() can only be called on repeated fields.");
}
@ -300,64 +327,63 @@ namespace Google.ProtocolBuffers {
return ((IList<object>) this[field]).Count;
}
#if !LITE
/// <summary>
/// See <see cref="IBuilder{TMessage, TBuilder}.MergeFrom(IMessageLite)" />
/// </summary>
public void MergeFrom(IMessage other) {
foreach (KeyValuePair<Descriptors.FieldDescriptor, object> fd in other.AllFields)
MergeField(fd.Key, fd.Value);
}
#endif
/// <summary>
/// Implementation of both <c>MergeFrom</c> methods.
/// </summary>
/// <param name="otherFields"></param>
private void MergeFields(IEnumerable<KeyValuePair<FieldDescriptor, object>> otherFields) {
public void MergeFrom(FieldSet other) {
// 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 IMessage interface itself cannot enforce immutability of
// the IMessageLite 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 otherFields) {
FieldDescriptor field = entry.Key;
object existingValue;
fields.TryGetValue(field, out existingValue);
if (field.IsRepeated) {
if (existingValue == null) {
existingValue = new List<object>();
fields[field] = existingValue;
}
IList<object> list = (IList<object>) existingValue;
foreach (object otherValue in (IEnumerable) entry.Value) {
list.Add(otherValue);
}
} else if (field.MappedType == MappedType.Message && existingValue != null) {
IMessage existingMessage = (IMessage)existingValue;
IMessage merged = existingMessage.WeakToBuilder()
.WeakMergeFrom((IMessage) entry.Value)
.WeakBuild();
this[field] = merged;
} else {
this[field] = entry.Value;
}
foreach (KeyValuePair<IFieldDescriptorLite, object> entry in other.fields) {
MergeField(entry.Key, entry.Value);
}
}
/// <summary>
/// See <see cref="IBuilder{TMessage, TBuilder}.MergeFrom(IMessage)" />
/// </summary>
public void MergeFrom(IMessage other) {
MergeFields(other.AllFields);
}
/// <summary>
/// Like <see cref="MergeFrom(IMessage)"/>, but merges from another <c>FieldSet</c>.
/// </summary>
public void MergeFrom(FieldSet other) {
MergeFields(other.fields);
private void MergeField(IFieldDescriptorLite field, object mergeValue) {
object existingValue;
fields.TryGetValue(field, out existingValue);
if (field.IsRepeated) {
if (existingValue == null) {
existingValue = new List<object>();
fields[field] = existingValue;
}
IList<object> list = (IList<object>) existingValue;
foreach (object otherValue in (IEnumerable)mergeValue) {
list.Add(otherValue);
}
} else if (field.MappedType == MappedType.Message && existingValue != null) {
IMessageLite existingMessage = (IMessageLite)existingValue;
IMessageLite merged = existingMessage.WeakToBuilder()
.WeakMergeFrom((IMessageLite)mergeValue)
.WeakBuild();
this[field] = merged;
} else {
this[field] = mergeValue;
}
}
/// <summary>
/// See <see cref="IMessage.WriteTo(CodedOutputStream)" />.
/// See <see cref="IMessageLite.WriteTo(CodedOutputStream)" />.
/// </summary>
public void WriteTo(CodedOutputStream output) {
foreach (KeyValuePair<FieldDescriptor, object> entry in fields) {
foreach (KeyValuePair<IFieldDescriptorLite, object> entry in fields) {
WriteField(entry.Key, entry.Value, output);
}
}
@ -365,9 +391,9 @@ namespace Google.ProtocolBuffers {
/// <summary>
/// Writes a single field to a CodedOutputStream.
/// </summary>
public void WriteField(FieldDescriptor field, Object value, CodedOutputStream output) {
if (field.IsExtension && field.ContainingType.Options.MessageSetWireFormat) {
output.WriteMessageSetExtension(field.FieldNumber, (IMessage) value);
public void WriteField(IFieldDescriptorLite field, Object value, CodedOutputStream output) {
if (field.IsExtension && field.MessageSetWireFormat) {
output.WriteMessageSetExtension(field.FieldNumber, (IMessageLite) value);
} else {
if (field.IsRepeated) {
IEnumerable valueList = (IEnumerable) value;
@ -395,18 +421,18 @@ namespace Google.ProtocolBuffers {
}
/// <summary>
/// See <see cref="IMessage.SerializedSize" />. It's up to the caller to
/// See <see cref="IMessageLite.SerializedSize" />. It's up to the caller to
/// cache the resulting size if desired.
/// </summary>
public int SerializedSize {
get {
int size = 0;
foreach (KeyValuePair<FieldDescriptor, object> entry in fields) {
FieldDescriptor field = entry.Key;
foreach (KeyValuePair<IFieldDescriptorLite, object> entry in fields) {
IFieldDescriptorLite field = entry.Key;
object value = entry.Value;
if (field.IsExtension && field.ContainingType.Options.MessageSetWireFormat) {
size += CodedOutputStream.ComputeMessageSetExtensionSize(field.FieldNumber, (IMessage)value);
if (field.IsExtension && field.MessageSetWireFormat) {
size += CodedOutputStream.ComputeMessageSetExtensionSize(field.FieldNumber, (IMessageLite)value);
} else {
if (field.IsRepeated) {
IEnumerable valueList = (IEnumerable)value;
@ -440,7 +466,7 @@ namespace Google.ProtocolBuffers {
/// </remarks>
/// <exception cref="ArgumentException">The value is not of the right type.</exception>
/// <exception cref="ArgumentNullException">The value is null.</exception>
private static void VerifyType(FieldDescriptor field, object value) {
private static void VerifyType(IFieldDescriptorLite field, object value) {
ThrowHelper.ThrowIfNull(value, "value");
bool isValid = false;
switch (field.MappedType) {
@ -454,12 +480,17 @@ namespace Google.ProtocolBuffers {
case MappedType.String: isValid = value is string; break;
case MappedType.ByteString: isValid = value is ByteString; break;
case MappedType.Enum:
EnumValueDescriptor enumValue = value as EnumValueDescriptor;
isValid = enumValue != null && enumValue.EnumDescriptor == field.EnumType;
IEnumLite enumValue = value as IEnumLite;
isValid = enumValue != null && field.EnumType.IsValidValue(enumValue);
break;
case MappedType.Message:
IMessage messageValue = value as IMessage;
isValid = messageValue != null && messageValue.DescriptorForType == field.MessageType;
IMessageLite messageValue = value as IMessageLite;
isValid = messageValue != null;
#if !LITE
if (isValid && messageValue is IMessage && field is FieldDescriptor) {
isValid = ((IMessage) messageValue).DescriptorForType == ((FieldDescriptor) field).MessageType;
}
#endif
break;
}
@ -468,10 +499,16 @@ namespace Google.ProtocolBuffers {
// the stack trace which exact call failed, since the whole chain is
// considered one line of code. So, let's make sure to include the
// field name and other useful info in the exception.
throw new ArgumentException("Wrong object type used with protocol message reflection. "
+ "Message type \"" + field.ContainingType.FullName
+ "\", field \"" + (field.IsExtension ? field.FullName : field.Name)
+ "\", value was type \"" + value.GetType().Name + "\".");
string message = "Wrong object type used with protocol message reflection.";
#if !LITE
Google.ProtocolBuffers.Descriptors.FieldDescriptor fieldinfo = field as Google.ProtocolBuffers.Descriptors.FieldDescriptor;
if (fieldinfo != null) {
message += "Message type \"" + fieldinfo.ContainingType.FullName;
message += "\", field \"" + (fieldinfo.IsExtension ? fieldinfo.FullName : fieldinfo.Name);
message += "\", value was type \"" + value.GetType().Name + "\".";
}
#endif
throw new ArgumentException(message);
}
}
}

@ -148,16 +148,20 @@ namespace Google.ProtocolBuffers {
}
} else if (field.MappedType == MappedType.Message && HasField(field)) {
// Merge singular embedded messages
IMessage oldValue = (IMessage)this[field];
IMessageLite oldValue = (IMessageLite)this[field];
this[field] = oldValue.WeakCreateBuilderForType()
.WeakMergeFrom(oldValue)
.WeakMergeFrom((IMessage)entry.Value)
.WeakMergeFrom((IMessageLite)entry.Value)
.WeakBuildPartial();
} else {
// Just overwrite
this[field] = entry.Value;
}
}
//Fix for unknown fields not merging, see java's AbstractMessage.Builder<T> line 236
MergeUnknownFields(other.UnknownFields);
return ThisBuilder;
}

@ -0,0 +1,117 @@
#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;
namespace Google.ProtocolBuffers {
/// <summary>
/// All generated protocol message builder classes extend this class. It implements
/// most of the IBuilder interface using reflection. Users can ignore this class
/// as an implementation detail.
/// </summary>
public abstract class GeneratedBuilderLite<TMessage, TBuilder> : AbstractBuilderLite<TMessage, TBuilder>
where TMessage : GeneratedMessageLite<TMessage, TBuilder>
where TBuilder : GeneratedBuilderLite<TMessage, TBuilder> {
/// <summary>
/// Returns the message being built at the moment.
/// </summary>
protected abstract TMessage MessageBeingBuilt { get; }
public override TBuilder MergeFrom(IMessageLite other) {
//do nothing, Lite runtime does not support cross-message merges
return ThisBuilder;
}
public abstract TBuilder MergeFrom(TMessage other);
public override bool IsInitialized {
get { return MessageBeingBuilt.IsInitialized; }
}
/// <summary>
/// Adds all of the specified values to the given collection.
/// </summary>
/// <exception cref="ArgumentNullException">Any element of the list is null</exception>
protected void AddRange<T>(IEnumerable<T> source, IList<T> destination) {
ThrowHelper.ThrowIfNull(source);
// We only need to check this for nullable types.
if (default(T) == null) {
ThrowHelper.ThrowIfAnyNull(source);
}
List<T> list = destination as List<T>;
if (list != null) {
list.AddRange(source);
} else {
foreach (T element in source) {
destination.Add(element);
}
}
}
/// <summary>
/// Called by derived classes to parse an unknown field.
/// </summary>
/// <returns>true unless the tag is an end-group tag</returns>
[CLSCompliant(false)]
protected virtual bool ParseUnknownField(CodedInputStream input,
ExtensionRegistry extensionRegistry, uint tag) {
return input.SkipField(tag);
}
/// <summary>
/// Like Build(), but will wrap UninitializedMessageException in
/// InvalidProtocolBufferException.
/// </summary>
public TMessage BuildParsed() {
if (!IsInitialized) {
throw new UninitializedMessageException(MessageBeingBuilt).AsInvalidProtocolBufferException();
}
return BuildPartial();
}
/// <summary>
/// Implementation of <see cref="IBuilder{TMessage, TBuilder}.Build" />.
/// </summary>
public override TMessage Build() {
// If the message is null, we'll throw a more appropriate exception in BuildPartial.
if (MessageBeingBuilt != null && !IsInitialized) {
throw new UninitializedMessageException(MessageBeingBuilt);
}
return BuildPartial();
}
}
}

@ -39,6 +39,7 @@ using System.Reflection;
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers {
/// <summary>
/// Base type for all generated extensions.
/// </summary>
@ -65,7 +66,7 @@ namespace Google.ProtocolBuffers {
public abstract class GeneratedExtensionBase<TExtension> {
private readonly FieldDescriptor descriptor;
private readonly IMessage messageDefaultInstance;
private readonly IMessageLite messageDefaultInstance;
protected GeneratedExtensionBase(FieldDescriptor descriptor, Type singularExtensionType) {
if (!descriptor.IsExtension) {
@ -79,7 +80,8 @@ namespace Google.ProtocolBuffers {
if (defaultInstanceProperty == null) {
throw new ArgumentException("No public static DefaultInstance property for type " + typeof(TExtension).Name);
}
messageDefaultInstance = (IMessage)defaultInstanceProperty.GetValue(null, null);
messageDefaultInstance = (IMessageLite)defaultInstanceProperty.GetValue(null, null);
}
}
@ -87,10 +89,14 @@ namespace Google.ProtocolBuffers {
get { return descriptor; }
}
public int Number {
get { return Descriptor.FieldNumber; }
}
/// <summary>
/// Returns the default message instance for extensions which are message types.
/// </summary>
public IMessage MessageDefaultInstance {
public IMessageLite MessageDefaultInstance {
get { return messageDefaultInstance; }
}
@ -107,7 +113,7 @@ namespace Google.ProtocolBuffers {
// This should not happen in normal use. But, to be nice, we'll
// copy the message to whatever type the caller was expecting.
return MessageDefaultInstance.WeakCreateBuilderForType()
.WeakMergeFrom((IMessage)value).WeakBuild();
.WeakMergeFrom((IMessageLite)value).WeakBuild();
}
case MappedType.Enum:
// Just return a boxed int - that can be unboxed to the enum

@ -0,0 +1,294 @@
#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.Collections;
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers {
public interface IGeneratedExtensionLite {
int Number { get; }
object ContainingType { get; }
IMessageLite MessageDefaultInstance { get; }
IFieldDescriptorLite Descriptor { get; }
}
public class ExtensionDescriptorLite : IFieldDescriptorLite {
private readonly string fullName;
private readonly IEnumLiteMap enumTypeMap;
private readonly int number;
private readonly FieldType type;
private readonly bool isRepeated;
private readonly bool isPacked;
private readonly MappedType mapType;
private readonly object defaultValue;
public ExtensionDescriptorLite(string fullName, IEnumLiteMap enumTypeMap, int number, FieldType type, object defaultValue, bool isRepeated, bool isPacked) {
this.fullName = fullName;
this.enumTypeMap = enumTypeMap;
this.number = number;
this.type = type;
this.mapType = FieldMappingAttribute.MappedTypeFromFieldType(type);
this.isRepeated = isRepeated;
this.isPacked = isPacked;
this.defaultValue = defaultValue;
}
public string FullName { get { return fullName; } }
public bool IsRepeated {
get { return isRepeated; }
}
public bool IsRequired {
get { return false; }
}
public bool IsPacked {
get { return isPacked; }
}
public bool IsExtension {
get { return true; }
}
/// <summary>
/// This is not supported and assertions are made to ensure this does not exist on extensions of Lite types
/// </summary>
public bool MessageSetWireFormat {
get { return false; }
}
public int FieldNumber {
get { return number; }
}
public IEnumLiteMap EnumType {
get { return enumTypeMap; }
}
public FieldType FieldType {
get { return type; }
}
public MappedType MappedType {
get { return mapType; }
}
public object DefaultValue {
get { return defaultValue; }
}
public int CompareTo(IFieldDescriptorLite other) {
return FieldNumber.CompareTo(other.FieldNumber);
}
}
public class GeneratedRepeatExtensionLite<TContainingType, TExtensionType> : GeneratedExtensionLite<TContainingType, IList<TExtensionType>>
where TContainingType : IMessageLite {
public GeneratedRepeatExtensionLite(string fullName, TContainingType containingTypeDefaultInstance,
IMessageLite messageDefaultInstance, IEnumLiteMap enumTypeMap, int number, FieldType type, bool isPacked) :
base(fullName, containingTypeDefaultInstance, new List<TExtensionType>(), messageDefaultInstance, enumTypeMap, number, type, isPacked) {
}
public override object ToReflectionType(object value) {
IList<object> result = new List<object>();
foreach (object element in (IEnumerable) value) {
result.Add(SingularToReflectionType(element));
}
return result;
}
public override object FromReflectionType(object value) {
// Must convert the whole list.
List<TExtensionType> result = new List<TExtensionType>();
foreach (object element in (IEnumerable)value) {
result.Add((TExtensionType)SingularFromReflectionType(element));
}
return result;
}
}
public class GeneratedExtensionLite<TContainingType, TExtensionType> : IGeneratedExtensionLite
where TContainingType : IMessageLite {
private readonly TContainingType containingTypeDefaultInstance;
private readonly TExtensionType defaultValue;
private readonly IMessageLite messageDefaultInstance;
private readonly ExtensionDescriptorLite descriptor;
// We can't always initialize a GeneratedExtension when we first construct
// it due to initialization order difficulties (namely, the default
// instances may not have been constructed yet). So, we construct an
// uninitialized GeneratedExtension once, then call internalInit() on it
// later. Generated code will always call internalInit() on all extensions
// as part of the static initialization code, and internalInit() throws an
// exception if called more than once, so this method is useless to users.
protected GeneratedExtensionLite(
TContainingType containingTypeDefaultInstance,
TExtensionType defaultValue,
IMessageLite messageDefaultInstance,
ExtensionDescriptorLite descriptor) {
this.containingTypeDefaultInstance = containingTypeDefaultInstance;
this.messageDefaultInstance = messageDefaultInstance;
this.defaultValue = defaultValue;
this.descriptor = descriptor;
}
/** For use by generated code only. */
public GeneratedExtensionLite(
string fullName,
TContainingType containingTypeDefaultInstance,
TExtensionType defaultValue,
IMessageLite messageDefaultInstance,
IEnumLiteMap enumTypeMap,
int number,
FieldType type)
: this(containingTypeDefaultInstance, defaultValue, messageDefaultInstance,
new ExtensionDescriptorLite(fullName, enumTypeMap, number, type, defaultValue,
false /* isRepeated */, false /* isPacked */)) {
}
private static readonly IList<object> Empty = new object[0];
/** Repeating fields: For use by generated code only. */
protected GeneratedExtensionLite(
string fullName,
TContainingType containingTypeDefaultInstance,
TExtensionType defaultValue,
IMessageLite messageDefaultInstance,
IEnumLiteMap enumTypeMap,
int number,
FieldType type,
bool isPacked)
: this(containingTypeDefaultInstance, defaultValue, messageDefaultInstance,
new ExtensionDescriptorLite(fullName, enumTypeMap, number, type, Empty,
true /* isRepeated */, isPacked)) {
}
/// <summary>
/// Returns information about this extension
/// </summary>
public IFieldDescriptorLite Descriptor {
get { return descriptor; }
}
/// <summary>
/// Returns the default value for this extension
/// </summary>
public TExtensionType DefaultValue {
get { return defaultValue; }
}
/// <summary>
/// used for the extension registry
/// </summary>
object IGeneratedExtensionLite.ContainingType {
get { return ContainingTypeDefaultInstance; }
}
/**
* Default instance of the type being extended, used to identify that type.
*/
public TContainingType ContainingTypeDefaultInstance {
get {
return containingTypeDefaultInstance;
}
}
/** Get the field number. */
public int Number {
get {
return descriptor.FieldNumber;
}
}
/**
* If the extension is an embedded message, this is the default instance of
* that type.
*/
public IMessageLite MessageDefaultInstance {
get {
return messageDefaultInstance;
}
}
/// <summary>
/// Converts from the type used by the native accessors to the type
/// used by reflection accessors. For example, the reflection accessors
/// for enums use EnumValueDescriptors but the native accessors use
/// the generated enum type.
/// </summary>
public virtual object ToReflectionType(object value) {
return SingularToReflectionType(value);
}
/// <summary>
/// Like ToReflectionType(object) but for a single element.
/// </summary>
public object SingularToReflectionType(object value) {
return descriptor.MappedType == MappedType.Enum
? descriptor.EnumType.FindValueByNumber((int)value)
: value;
}
public virtual object FromReflectionType(object value) {
return SingularFromReflectionType(value);
}
public object SingularFromReflectionType(object value) {
switch (Descriptor.MappedType) {
case MappedType.Message:
if (value is TExtensionType) {
return value;
} else {
// It seems the copy of the embedded message stored inside the
// extended message is not of the exact type the user was
// expecting. This can happen if a user defines a
// GeneratedExtension manually and gives it a different type.
// This should not happen in normal use. But, to be nice, we'll
// copy the message to whatever type the caller was expecting.
return MessageDefaultInstance.WeakCreateBuilderForType()
.WeakMergeFrom((IMessageLite)value).WeakBuild();
}
case MappedType.Enum:
// Just return a boxed int - that can be unboxed to the enum
IEnumLite enumValue = (IEnumLite)value;
return enumValue.Number;
default:
return value;
}
}
}
}

@ -99,13 +99,13 @@ namespace Google.ProtocolBuffers {
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 (IMessage element in (IEnumerable) this[field]) {
foreach (IMessageLite element in (IEnumerable) this[field]) {
if (!element.IsInitialized) {
return false;
}
}
} else {
if (HasField(field) && !((IMessage) this[field]).IsInitialized) {
if (HasField(field) && !((IMessageLite) this[field]).IsInitialized) {
return false;
}
}

@ -0,0 +1,132 @@
#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.Collections;
using System.Globalization;
using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers {
/// <summary>
/// All generated protocol message classes extend this class. It implements
/// most of the IMessage interface using reflection. Users
/// can ignore this class as an implementation detail.
/// </summary>
public abstract class GeneratedMessageLite<TMessage, TBuilder> : AbstractMessageLite<TMessage, TBuilder>
where TMessage : GeneratedMessageLite<TMessage, TBuilder>
where TBuilder : GeneratedBuilderLite<TMessage, TBuilder> {
protected abstract TMessage ThisMessage { get; }
public sealed override string ToString() {
using (System.IO.StringWriter wtr = new System.IO.StringWriter()) {
PrintTo(wtr);
return wtr.ToString();
}
}
/// <summary>
/// PrintTo() helper methods for Lite Runtime
/// </summary>
protected static void PrintField<T>(string name, IList<T> value, System.IO.TextWriter writer) {
foreach (T item in value)
PrintField(name, true, (object)item, writer);
}
/// <summary>
/// PrintTo() helper methods for Lite Runtime
/// </summary>
protected static void PrintField(string name, bool hasValue, object value, System.IO.TextWriter writer) {
if (!hasValue) return;
if (value is IMessageLite) {
writer.WriteLine("{0} {{", name);
((IMessageLite)value).PrintTo(writer);
writer.WriteLine("}");
} else if (value is ByteString || value is String) {
writer.Write("{0}: \"", name);
if(value is String)
EscapeBytes( System.Text.Encoding.UTF8.GetBytes((string)value), writer);
else
EscapeBytes(((ByteString)value), writer);
writer.WriteLine("\"");
} else if (value is bool) {
writer.WriteLine("{0}: {1}", name, (bool)value ? "true" : "false");
} else if (value is IEnumLite) {
writer.WriteLine("{0}: {1}", name, ((IEnumLite)value).Name);
}
else {
writer.WriteLine("{0}: {1}", name, ((IConvertible)value).ToString(CultureInfo.InvariantCulture));
}
}
/// <summary>
/// COPIED from TextFormat
/// Escapes bytes in the format used in protocol buffer text format, which
/// is the same as the format used for C string literals. All bytes
/// that are not printable 7-bit ASCII characters are escaped, as well as
/// backslash, single-quote, and double-quote characters. Characters for
/// which no defined short-hand escape sequence is defined will be escaped
/// using 3-digit octal sequences.
/// The returned value is guaranteed to be entirely ASCII.
/// </summary>
private static void EscapeBytes(IEnumerable<byte> input, System.IO.TextWriter writer) {
foreach (byte b in input) {
switch (b) {
// C# does not use \a or \v
case 0x07: writer.Write("\\a"); break;
case (byte)'\b': writer.Write("\\b"); break;
case (byte)'\f': writer.Write("\\f"); break;
case (byte)'\n': writer.Write("\\n"); break;
case (byte)'\r': writer.Write("\\r"); break;
case (byte)'\t': writer.Write("\\t"); break;
case 0x0b: writer.Write("\\v"); break;
case (byte)'\\': writer.Write("\\\\"); break;
case (byte)'\'': writer.Write("\\\'"); break;
case (byte)'"': writer.Write("\\\""); break;
default:
if (b >= 0x20 && b < 128) {
writer.Write((char)b);
} else {
writer.Write('\\');
writer.Write((char)('0' + ((b >> 6) & 3)));
writer.Write((char)('0' + ((b >> 3) & 7)));
writer.Write((char)('0' + (b & 7)));
}
break;
}
}
}
}
}

@ -47,12 +47,12 @@ namespace Google.ProtocolBuffers {
/// use explicit interface implemenation for the non-generic form. This mirrors
/// how IEnumerable and IEnumerable&lt;T&gt; work.
/// </summary>
public interface IBuilder {
public interface IBuilder : IBuilderLite {
/// <summary>
/// Returns true iff all required fields in the message and all
/// embedded messages are set.
/// </summary>
bool IsInitialized { get; }
new bool IsInitialized { get; }
/// <summary>
/// Only present in the nongeneric interface - useful for tests, but
@ -119,17 +119,17 @@ namespace Google.ProtocolBuffers {
#region Methods which are like those of the generic form, but without any knowledge of the type parameters
IBuilder WeakAddRepeatedField(FieldDescriptor field, object value);
IBuilder WeakClear();
new IBuilder WeakClear();
IBuilder WeakClearField(FieldDescriptor field);
IBuilder WeakMergeFrom(IMessage message);
IBuilder WeakMergeFrom(ByteString data);
IBuilder WeakMergeFrom(ByteString data, ExtensionRegistry registry);
IBuilder WeakMergeFrom(CodedInputStream input);
IBuilder WeakMergeFrom(CodedInputStream input, ExtensionRegistry registry);
IMessage WeakBuild();
IMessage WeakBuildPartial();
IBuilder WeakClone();
IMessage WeakDefaultInstanceForType { get; }
new IBuilder WeakMergeFrom(ByteString data);
new IBuilder WeakMergeFrom(ByteString data, ExtensionRegistry registry);
new IBuilder WeakMergeFrom(CodedInputStream input);
new IBuilder WeakMergeFrom(CodedInputStream input, ExtensionRegistry registry);
new IMessage WeakBuild();
new IMessage WeakBuildPartial();
new IBuilder WeakClone();
new IMessage WeakDefaultInstanceForType { get; }
#endregion
}
@ -139,7 +139,7 @@ namespace Google.ProtocolBuffers {
/// </summary>
/// <typeparam name="TMessage">Type of message</typeparam>
/// <typeparam name="TBuilder">Type of builder</typeparam>
public interface IBuilder<TMessage, TBuilder> : IBuilder
public interface IBuilder<TMessage, TBuilder> : IBuilder, IBuilderLite<TMessage, TBuilder>
where TMessage : IMessage<TMessage, TBuilder>
where TBuilder : IBuilder<TMessage, TBuilder> {
@ -148,22 +148,7 @@ namespace Google.ProtocolBuffers {
/// <summary>
/// Resets all fields to their default values.
/// </summary>
TBuilder Clear();
/// <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>
TBuilder MergeFrom(TMessage other);
new TBuilder Clear();
/// <summary>
/// Merge the specified other message which may be a different implementation of
@ -180,19 +165,19 @@ namespace Google.ProtocolBuffers {
/// <exception cref="UninitializedMessageException">the message
/// is missing one or more required fields; use BuildPartial to bypass
/// this check</exception>
TMessage Build();
new TMessage Build();
/// <summary>
/// Like Build(), but does not throw an exception if the message is missing
/// required fields. Instead, a partial message is returned.
/// </summary>
TMessage BuildPartial();
new TMessage BuildPartial();
/// <summary>
/// Clones this builder.
/// TODO(jonskeet): Explain depth of clone.
/// </summary>
TBuilder Clone();
new TBuilder Clone();
/// <summary>
/// Parses a message of this type from the input and merges it with this
@ -213,7 +198,7 @@ namespace Google.ProtocolBuffers {
/// Use BuildPartial to build, which ignores missing required fields.
/// </list>
/// </remarks>
TBuilder MergeFrom(CodedInputStream input);
new TBuilder MergeFrom(CodedInputStream input);
/// <summary>
/// Like MergeFrom(CodedInputStream), but also parses extensions.
@ -221,13 +206,13 @@ namespace Google.ProtocolBuffers {
/// in <paramref name="extensionRegistry"/>. Extensions not in the registry
/// will be treated as unknown fields.
/// </summary>
TBuilder MergeFrom(CodedInputStream input, ExtensionRegistry extensionRegistry);
new TBuilder MergeFrom(CodedInputStream input, ExtensionRegistry extensionRegistry);
/// <summary>
/// Get's the message's type's default instance.
/// <see cref="IMessage{TMessage}.DefaultInstanceForType" />
/// </summary>
TMessage DefaultInstanceForType { get; }
new TMessage DefaultInstanceForType { get; }
/// <summary>
/// Clears the field. This is exactly equivalent to calling the generated
@ -258,12 +243,12 @@ namespace Google.ProtocolBuffers {
/// write messages in this format.
/// </summary>
/// <param name="input"></param>
TBuilder MergeDelimitedFrom(Stream input);
new TBuilder MergeDelimitedFrom(Stream input);
/// <summary>
/// Like MergeDelimitedFrom(Stream) but supporting extensions.
/// </summary>
TBuilder MergeDelimitedFrom(Stream input, ExtensionRegistry extensionRegistry);
new TBuilder MergeDelimitedFrom(Stream input, ExtensionRegistry extensionRegistry);
#region Convenience methods
/// <summary>
@ -271,28 +256,28 @@ namespace Google.ProtocolBuffers {
/// it with the message being built. This is just a small wrapper around
/// MergeFrom(CodedInputStream).
/// </summary>
TBuilder MergeFrom(ByteString data);
new TBuilder MergeFrom(ByteString data);
/// <summary>
/// Parse <paramref name="data"/> as a message of this type and merge
/// it with the message being built. This is just a small wrapper around
/// MergeFrom(CodedInputStream, ExtensionRegistry).
/// MergeFrom(CodedInputStream, extensionRegistry).
/// </summary>
TBuilder MergeFrom(ByteString data, ExtensionRegistry extensionRegistry);
new TBuilder MergeFrom(ByteString data, ExtensionRegistry extensionRegistry);
/// <summary>
/// Parse <paramref name="data"/> as a message of this type and merge
/// it with the message being built. This is just a small wrapper around
/// MergeFrom(CodedInputStream).
/// </summary>
TBuilder MergeFrom(byte[] data);
new TBuilder MergeFrom(byte[] data);
/// <summary>
/// Parse <paramref name="data"/> as a message of this type and merge
/// it with the message being built. This is just a small wrapper around
/// MergeFrom(CodedInputStream, ExtensionRegistry).
/// MergeFrom(CodedInputStream, extensionRegistry).
/// </summary>
TBuilder MergeFrom(byte[] data, ExtensionRegistry extensionRegistry);
new TBuilder MergeFrom(byte[] data, ExtensionRegistry extensionRegistry);
/// <summary>
/// Parse <paramref name="input"/> as a message of this type and merge
@ -304,14 +289,14 @@ namespace Google.ProtocolBuffers {
/// to write your message and MmergeDelimitedFrom(Stream) to read it.
/// Despite usually reading the entire stream, this method never closes the stream.
/// </summary>
TBuilder MergeFrom(Stream input);
new TBuilder MergeFrom(Stream input);
/// <summary>
/// Parse <paramref name="input"/> as a message of this type and merge
/// it with the message being built. This is just a small wrapper around
/// MergeFrom(CodedInputStream, ExtensionRegistry).
/// MergeFrom(CodedInputStream, extensionRegistry).
/// </summary>
TBuilder MergeFrom(Stream input, ExtensionRegistry extensionRegistry);
new TBuilder MergeFrom(Stream input, ExtensionRegistry extensionRegistry);
#endregion
}
}

@ -0,0 +1,210 @@
#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;
namespace Google.ProtocolBuffers {
/// <summary>
/// Non-generic interface for all members whose signatures don't require knowledge of
/// the type being built. The generic interface extends this one. Some methods return
/// either an IBuilder or an IMessage; in these cases the generic interface redeclares
/// the same method with a type-specific signature. Implementations are encouraged to
/// use explicit interface implemenation for the non-generic form. This mirrors
/// how IEnumerable and IEnumerable&lt;T&gt; work.
/// </summary>
public interface IBuilderLite {
/// <summary>
/// Returns true iff all required fields in the message and all
/// embedded messages are set.
/// </summary>
bool IsInitialized { get; }
IBuilderLite WeakClear();
IBuilderLite WeakMergeFrom(IMessageLite message);
IBuilderLite WeakMergeFrom(ByteString data);
IBuilderLite WeakMergeFrom(ByteString data, ExtensionRegistry registry);
IBuilderLite WeakMergeFrom(CodedInputStream input);
IBuilderLite WeakMergeFrom(CodedInputStream input, ExtensionRegistry registry);
IMessageLite WeakBuild();
IMessageLite WeakBuildPartial();
IBuilderLite WeakClone();
IMessageLite WeakDefaultInstanceForType { get; }
}
/// <summary>
/// Interface implemented by Protocol Message builders.
/// TODO(jonskeet): Consider "SetXXX" methods returning the builder, as well as the properties.
/// </summary>
/// <typeparam name="TMessage">Type of message</typeparam>
/// <typeparam name="TBuilder">Type of builder</typeparam>
public interface IBuilderLite<TMessage, TBuilder> : IBuilderLite
where TMessage : IMessageLite<TMessage, TBuilder>
where TBuilder : IBuilderLite<TMessage, TBuilder> {
/// <summary>
/// Resets all fields to their default values.
/// </summary>
TBuilder Clear();
/// <summary>
/// Merge the specified other message which may be a different implementation of
/// the same message descriptor.
/// </summary>
TBuilder MergeFrom(IMessageLite other);
/// <summary>
/// Constructs the final message. Once this is called, this Builder instance
/// is no longer valid, and calling any other method may throw a
/// NullReferenceException. If you need to continue working with the builder
/// after calling Build, call Clone first.
/// </summary>
/// <exception cref="UninitializedMessageException">the message
/// is missing one or more required fields; use BuildPartial to bypass
/// this check</exception>
TMessage Build();
/// <summary>
/// Like Build(), but does not throw an exception if the message is missing
/// required fields. Instead, a partial message is returned.
/// </summary>
TMessage BuildPartial();
/// <summary>
/// Clones this builder.
/// TODO(jonskeet): Explain depth of clone.
/// </summary>
TBuilder Clone();
/// <summary>
/// Parses a message of this type from the input and merges it with this
/// message, as if using MergeFrom(IMessage&lt;T&gt;).
/// </summary>
/// <remarks>
/// Warning: This does not verify that all required fields are present
/// in the input message. If you call Build() without setting all
/// required fields, it will throw an UninitializedMessageException.
/// There are a few good ways to deal with this:
/// <list>
/// <item>Call IsInitialized to verify to verify that all required fields are
/// set before building.</item>
/// <item>Parse the message separately using one of the static ParseFrom
/// methods, then use MergeFrom(IMessage&lt;T&gt;) to merge it with
/// this one. ParseFrom will throw an InvalidProtocolBufferException
/// (an IOException) if some required fields are missing.
/// Use BuildPartial to build, which ignores missing required fields.
/// </list>
/// </remarks>
TBuilder MergeFrom(CodedInputStream input);
/// <summary>
/// Like MergeFrom(CodedInputStream), but also parses extensions.
/// The extensions that you want to be able to parse must be registered
/// in <paramref name="extensionRegistry"/>. Extensions not in the registry
/// will be treated as unknown fields.
/// </summary>
TBuilder MergeFrom(CodedInputStream input, ExtensionRegistry extensionRegistry);
/// <summary>
/// Get's the message's type's default instance.
/// <see cref="IMessageLite{TMessage}.DefaultInstanceForType" />
/// </summary>
TMessage DefaultInstanceForType { get; }
/// <summary>
/// Like MergeFrom(Stream), but does not read until the end of the file.
/// Instead, the size of the message (encoded as a varint) is read first,
/// then the message data. Use Message.WriteDelimitedTo(Stream) to
/// write messages in this format.
/// </summary>
/// <param name="input"></param>
TBuilder MergeDelimitedFrom(Stream input);
/// <summary>
/// Like MergeDelimitedFrom(Stream) but supporting extensions.
/// </summary>
TBuilder MergeDelimitedFrom(Stream input, ExtensionRegistry extensionRegistry);
#region Convenience methods
/// <summary>
/// Parse <paramref name="data"/> as a message of this type and merge
/// it with the message being built. This is just a small wrapper around
/// MergeFrom(CodedInputStream).
/// </summary>
TBuilder MergeFrom(ByteString data);
/// <summary>
/// Parse <paramref name="data"/> as a message of this type and merge
/// it with the message being built. This is just a small wrapper around
/// MergeFrom(CodedInputStream, ExtensionRegistry).
/// </summary>
TBuilder MergeFrom(ByteString data, ExtensionRegistry extensionRegistry);
/// <summary>
/// Parse <paramref name="data"/> as a message of this type and merge
/// it with the message being built. This is just a small wrapper around
/// MergeFrom(CodedInputStream).
/// </summary>
TBuilder MergeFrom(byte[] data);
/// <summary>
/// Parse <paramref name="data"/> as a message of this type and merge
/// it with the message being built. This is just a small wrapper around
/// MergeFrom(CodedInputStream, ExtensionRegistry).
/// </summary>
TBuilder MergeFrom(byte[] data, ExtensionRegistry extensionRegistry);
/// <summary>
/// Parse <paramref name="input"/> as a message of this type and merge
/// it with the message being built. This is just a small wrapper around
/// MergeFrom(CodedInputStream). Note that this method always reads
/// the entire input (unless it throws an exception). If you want it to
/// stop earlier, you will need to wrap the input in a wrapper
/// stream which limits reading. Or, use IMessage.WriteDelimitedTo(Stream)
/// to write your message and MmergeDelimitedFrom(Stream) to read it.
/// Despite usually reading the entire stream, this method never closes the stream.
/// </summary>
TBuilder MergeFrom(Stream input);
/// <summary>
/// Parse <paramref name="input"/> as a message of this type and merge
/// it with the message being built. This is just a small wrapper around
/// MergeFrom(CodedInputStream, ExtensionRegistry).
/// </summary>
TBuilder MergeFrom(Stream input, ExtensionRegistry extensionRegistry);
#endregion
}
}

@ -43,7 +43,7 @@ namespace Google.ProtocolBuffers {
/// Non-generic interface used for all parts of the API which don't require
/// any type knowledge.
/// </summary>
public interface IMessage {
public interface IMessage : IMessageLite {
/// <summary>
/// Returns the message's type's descriptor. This differs from the
/// Descriptor property of each generated message class in that this
@ -110,7 +110,7 @@ namespace Google.ProtocolBuffers {
/// Returns true iff all required fields in the message and all embedded
/// messages are set.
/// </summary>
bool IsInitialized { get; }
new bool IsInitialized { get; }
/// <summary>
/// Serializes the message and writes it to the given output stream.
@ -124,7 +124,7 @@ namespace Google.ProtocolBuffers {
/// 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>
void WriteTo(CodedOutputStream output);
new void WriteTo(CodedOutputStream output);
/// <summary>
/// Like WriteTo(Stream) but writes the size of the message as a varint before
@ -134,13 +134,13 @@ namespace Google.ProtocolBuffers {
/// YourMessageType.ParseDelimitedFrom(Stream) to parse messages written by this method.
/// </summary>
/// <param name="output"></param>
void WriteDelimitedTo(Stream output);
new void WriteDelimitedTo(Stream 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>
int SerializedSize { get; }
new int SerializedSize { get; }
#region Comparison and hashing
/// <summary>
@ -149,13 +149,13 @@ namespace Google.ProtocolBuffers {
/// (as defined by DescriptorForType) and has identical values
/// for all its fields.
/// </summary>
bool Equals(object other);
new bool Equals(object other);
/// <summary>
/// Returns the hash code value for this message.
/// TODO(jonskeet): Specify the hash algorithm, but better than the Java one!
/// </summary>
int GetHashCode();
new int GetHashCode();
#endregion
#region Convenience methods
@ -163,19 +163,19 @@ namespace Google.ProtocolBuffers {
/// Converts the message to a string in protocol buffer text format.
/// This is just a trivial wrapper around TextFormat.PrintToString.
/// </summary>
string ToString();
new string ToString();
/// <summary>
/// Serializes the message to a ByteString. This is a trivial wrapper
/// around WriteTo(CodedOutputStream).
/// </summary>
ByteString ToByteString();
new ByteString ToByteString();
/// <summary>
/// Serializes the message to a byte array. This is a trivial wrapper
/// around WriteTo(CodedOutputStream).
/// </summary>
byte[] ToByteArray();
new byte[] ToByteArray();
/// <summary>
/// Serializes the message and writes it to the given stream.
@ -183,7 +183,7 @@ namespace Google.ProtocolBuffers {
/// does not flush or close the stream.
/// </summary>
/// <param name="output"></param>
void WriteTo(Stream output);
new void WriteTo(Stream output);
#endregion
/// <summary>
@ -191,19 +191,19 @@ namespace Google.ProtocolBuffers {
/// is typically implemented by strongly typed messages by just returning
/// the result of CreateBuilderForType.
/// </summary>
IBuilder WeakCreateBuilderForType();
new IBuilder WeakCreateBuilderForType();
/// <summary>
/// Creates a builder with the same contents as this message. This
/// is typically implemented by strongly typed messages by just returning
/// the result of ToBuilder.
/// </summary>
IBuilder WeakToBuilder();
new IBuilder WeakToBuilder();
IMessage WeakDefaultInstanceForType { get; }
new IMessage WeakDefaultInstanceForType { get; }
}
public interface IMessage<TMessage> : IMessage {
public interface IMessage<TMessage> : IMessage, IMessageLite<TMessage> {
/// <summary>
/// Returns an instance of this message type with all fields set to
/// their default values. This may or may not be a singleton. This differs
@ -211,26 +211,26 @@ namespace Google.ProtocolBuffers {
/// method is an abstract method of IMessage whereas DefaultInstance is
/// a static property of a specific class. They return the same thing.
/// </summary>
TMessage DefaultInstanceForType { get; }
new TMessage DefaultInstanceForType { get; }
}
/// <summary>
/// Type-safe interface for all generated messages to implement.
/// </summary>
public interface IMessage<TMessage, TBuilder> : IMessage<TMessage>
public interface IMessage<TMessage, TBuilder> : IMessage<TMessage>, IMessageLite<TMessage, TBuilder>
where TMessage : IMessage<TMessage, TBuilder>
where TBuilder : IBuilder<TMessage, TBuilder> {
#region Builders
/// <summary>
/// Constructs a new builder for a message of the same type as this message.
/// </summary>
TBuilder CreateBuilderForType();
new TBuilder CreateBuilderForType();
/// <summary>
/// Creates a builder with the same contents as this current instance.
/// This is typically implemented by strongly typed messages by just
/// returning the result of ToBuilder().
/// </summary>
TBuilder ToBuilder();
new TBuilder ToBuilder();
#endregion
}
}

@ -0,0 +1,179 @@
#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;
namespace Google.ProtocolBuffers {
/// <summary>
/// Non-generic interface used for all parts of the API which don't require
/// any type knowledge.
/// </summary>
public interface IMessageLite {
/// <summary>
/// Returns true iff all required fields in the message and all embedded
/// messages are set.
/// </summary>
bool IsInitialized { get; }
/// <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>
void WriteTo(CodedOutputStream output);
/// <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>
void WriteDelimitedTo(Stream 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>
int SerializedSize { get; }
#region Comparison and hashing
/// <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>
bool Equals(object other);
/// <summary>
/// Returns the hash code value for this message.
/// TODO(jonskeet): Specify the hash algorithm, but better than the Java one!
/// </summary>
int GetHashCode();
#endregion
#region Convenience methods
/// <summary>
/// Converts the message to a string in protocol buffer text format.
/// This is just a trivial wrapper around TextFormat.PrintToString.
/// </summary>
string ToString();
/// <summary>
/// Converts the message to a string.
/// </summary>
void PrintTo(TextWriter writer);
/// <summary>
/// Serializes the message to a ByteString. This is a trivial wrapper
/// around WriteTo(CodedOutputStream).
/// </summary>
ByteString ToByteString();
/// <summary>
/// Serializes the message to a byte array. This is a trivial wrapper
/// around WriteTo(CodedOutputStream).
/// </summary>
byte[] ToByteArray();
/// <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>
void WriteTo(Stream output);
#endregion
/// <summary>
/// Creates a builder for the type, but in a weakly typed manner. This
/// is typically implemented by strongly typed messages by just returning
/// the result of CreateBuilderForType.
/// </summary>
IBuilderLite WeakCreateBuilderForType();
/// <summary>
/// Creates a builder with the same contents as this message. This
/// is typically implemented by strongly typed messages by just returning
/// the result of ToBuilder.
/// </summary>
IBuilderLite WeakToBuilder();
IMessageLite WeakDefaultInstanceForType { get; }
}
public interface IMessageLite<TMessage> : IMessageLite {
/// <summary>
/// Returns an instance of this message type with all fields set to
/// their default values. This may or may not be a singleton. This differs
/// from the DefaultInstance property of each generated message class in that this
/// method is an abstract method of IMessage whereas DefaultInstance is
/// a static property of a specific class. They return the same thing.
/// </summary>
TMessage DefaultInstanceForType { get; }
}
/// <summary>
/// Type-safe interface for all generated messages to implement.
/// </summary>
public interface IMessageLite<TMessage, TBuilder> : IMessageLite<TMessage>
where TMessage : IMessageLite<TMessage, TBuilder>
where TBuilder : IBuilderLite<TMessage, TBuilder> {
#region Builders
/// <summary>
/// Constructs a new builder for a message of the same type as this message.
/// </summary>
TBuilder CreateBuilderForType();
/// <summary>
/// Creates a builder with the same contents as this current instance.
/// This is typically implemented by strongly typed messages by just
/// returning the result of ToBuilder().
/// </summary>
TBuilder ToBuilder();
#endregion
}
}

@ -74,6 +74,12 @@ using System.Runtime.CompilerServices;
"72f738140072bb69990bc4f98a21365de2c105e848974a3d210e938b0a56103c0662901efd6b78"+
"0ee6dbe977923d46a8fda18fb25c65dd73b149a5cd9f3100668b56649932dadd8cf5be52eb1dce"+
"ad5cedbf")]
[assembly: InternalsVisibleTo("Google.ProtocolBuffersLite.Test,PublicKey=" +
"00240000048000009400000006020000002400005253413100040000010001008179f2dd31a648" +
"2a2359dbe33e53701167a888e7c369a9ae3210b64f93861d8a7d286447e58bc167e3d99483beda" +
"72f738140072bb69990bc4f98a21365de2c105e848974a3d210e938b0a56103c0662901efd6b78" +
"0ee6dbe977923d46a8fda18fb25c65dd73b149a5cd9f3100668b56649932dadd8cf5be52eb1dce" +
"ad5cedbf")]
[assembly: InternalsVisibleTo("ProtoGen,PublicKey=" +
"00240000048000009400000006020000002400005253413100040000010001006d739020e13bdc" +
"038e86fa8aa5e1b13aae65d3ae79d622816c6067ab5b6955be50cc887130117582349208c13a55" +

@ -80,10 +80,18 @@
<ItemGroup>
<Reference Include="mscorlib" />
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="AbstractBuilder.cs" />
<Compile Include="AbstractBuilderLite.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="AbstractMessage.cs" />
<Compile Include="AbstractMessageLite.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="ByteString.cs" />
<Compile Include="Collections\Enumerables.cs" />
<Compile Include="Collections\IPopsicleList.cs" />
@ -116,10 +124,16 @@
<Compile Include="Descriptors\PackageDescriptor.cs" />
<Compile Include="Descriptors\ServiceDescriptor.cs" />
<Compile Include="DynamicMessage.cs" />
<Compile Include="EnumLite.cs" />
<Compile Include="ExtendableBuilder.cs" />
<Compile Include="ExtendableBuilderLite.cs" />
<Compile Include="ExtendableMessage.cs" />
<Compile Include="ExtensionInfo.cs" />
<Compile Include="ExtendableMessageLite.cs" />
<Compile Include="ExtensionInfo.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="ExtensionRegistry.cs" />
<Compile Include="ExtensionRegistryLite.cs" />
<Compile Include="FieldAccess\ReflectionUtil.cs" />
<Compile Include="FieldAccess\SingleEnumAccessor.cs" />
<Compile Include="FieldAccess\SingleMessageAccessor.cs" />
@ -131,12 +145,19 @@
<Compile Include="FieldAccess\RepeatedMessageAccessor.cs" />
<Compile Include="FieldSet.cs" />
<Compile Include="GeneratedBuilder.cs" />
<Compile Include="GeneratedBuilderLite.cs" />
<Compile Include="GeneratedExtensionLite.cs" />
<Compile Include="GeneratedMessageLite.cs" />
<Compile Include="GeneratedRepeatExtension.cs" />
<Compile Include="GeneratedSingleExtension.cs" />
<Compile Include="GeneratedMessage.cs" />
<Compile Include="IBuilder.cs" />
<Compile Include="GeneratedExtensionBase.cs" />
<Compile Include="IBuilderLite.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="IMessage.cs" />
<Compile Include="IMessageLite.cs" />
<Compile Include="InvalidProtocolBufferException.cs" />
<Compile Include="IRpcChannel.cs" />
<Compile Include="IRpcController.cs" />

@ -0,0 +1,115 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{6969BDCE-D925-43F3-94AC-A531E6DF2591}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Google.ProtocolBuffers</RootNamespace>
<AssemblyName>Google.ProtocolBuffersLite</AssemblyName>
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>Properties\Google.ProtocolBuffers.snk</AssemblyOriginatorKeyFile>
<FileUpgradeFlags>
</FileUpgradeFlags>
<OldToolsVersion>3.5</OldToolsVersion>
<UpgradeBackupLocation />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>TRACE;DEBUG;LITE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoStdLib>true</NoStdLib>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE;LITE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoStdLib>true</NoStdLib>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug_Silverlight2|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug_Silverlight2\</OutputPath>
<DefineConstants>DEBUG;TRACE;SILVERLIGHT2;LITE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoStdLib>true</NoStdLib>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release_Silverlight2|AnyCPU'">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release_Silverlight2\</OutputPath>
<DefineConstants>TRACE;SILVERLIGHT2;LITE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoStdLib>true</NoStdLib>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="mscorlib" />
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
</ItemGroup>
<ItemGroup>
<None Include="Properties\Google.ProtocolBuffers.snk" />
</ItemGroup>
<ItemGroup>
<Compile Include="AbstractBuilderLite.cs" />
<Compile Include="AbstractMessageLite.cs" />
<Compile Include="Collections\Dictionaries.cs" />
<Compile Include="Collections\Enumerables.cs" />
<Compile Include="Collections\IPopsicleList.cs" />
<Compile Include="Collections\Lists.cs" />
<Compile Include="Collections\PopsicleList.cs" />
<Compile Include="Collections\ReadOnlyDictionary.cs" />
<Compile Include="Descriptors\FieldMappingAttribute.cs" />
<Compile Include="Descriptors\FieldType.cs" />
<Compile Include="Descriptors\MappedType.cs" />
<Compile Include="EnumLite.cs" />
<Compile Include="ExtendableBuilderLite.cs" />
<Compile Include="ExtendableMessageLite.cs" />
<Compile Include="FieldSet.cs" />
<Compile Include="GeneratedBuilderLite.cs" />
<Compile Include="GeneratedExtensionLite.cs" />
<Compile Include="GeneratedMessageLite.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="ByteString.cs" />
<Compile Include="CodedInputStream.cs" />
<Compile Include="CodedOutputStream.cs" />
<Compile Include="ExtensionRegistryLite.cs" />
<Compile Include="IBuilderLite.cs" />
<Compile Include="IMessageLite.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="InvalidProtocolBufferException.cs" />
<Compile Include="ThrowHelper.cs" />
<Compile Include="UninitializedMessageException.cs" />
<Compile Include="WireFormat.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" Condition=" '$(Configuration)' != 'Silverlight2' " />
<Import Project="$(MSBuildExtensionsPath)\Microsoft\Silverlight\v2.0\Microsoft.Silverlight.CSharp.targets" Condition=" '$(Configuration)' == 'Silverlight2' " />
<!-- 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.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

@ -50,6 +50,18 @@ namespace Google.ProtocolBuffers
{
private readonly IDictionary<TKey, TValue> wrapped = new Dictionary<TKey, TValue>();
public SortedList()
{
}
public SortedList(IDictionary<TKey, TValue> dictionary)
{
foreach (KeyValuePair<TKey, TValue> entry in dictionary)
{
Add(entry.Key, entry.Value);
}
}
public void Add(TKey key, TValue value)
{
wrapped.Add(key, value);

@ -170,13 +170,19 @@ namespace Google.ProtocolBuffers {
}
case FieldType.Enum: {
generator.Print(((EnumValueDescriptor) value).Name);
if (value is IEnumLite && !(value is EnumValueDescriptor)) {
throw new NotSupportedException("Lite enumerations are not supported.");
}
generator.Print(((EnumValueDescriptor)value).Name);
break;
}
case FieldType.Message:
case FieldType.Group:
Print((IMessage) value, generator);
if (value is IMessageLite && !(value is IMessage)) {
throw new NotSupportedException("Lite messages are not supported.");
}
Print((IMessage)value, generator);
break;
}
}
@ -576,7 +582,9 @@ namespace Google.ProtocolBuffers {
if (extension == null) {
subBuilder = builder.CreateBuilderForField(field);
} else {
subBuilder = extension.DefaultInstance.WeakCreateBuilderForType();
subBuilder = extension.DefaultInstance.WeakCreateBuilderForType() as IBuilder;
if (subBuilder == null)
throw new NotSupportedException("Lite messages are not supported.");
}
while (!tokenizer.TryConsume(endToken)) {

@ -36,8 +36,10 @@ using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
#if !LITE
using Google.ProtocolBuffers.Collections;
using Google.ProtocolBuffers.Descriptors;
#endif
namespace Google.ProtocolBuffers {
/// <summary>
@ -47,16 +49,10 @@ namespace Google.ProtocolBuffers {
private readonly IList<string> missingFields;
public UninitializedMessageException(IMessage message)
: this(FindMissingFields(message)) {
}
private UninitializedMessageException(IList<string> missingFields)
: base(BuildDescription(missingFields)) {
this.missingFields = Lists.AsReadOnly(missingFields);
this.missingFields = new List<string>(missingFields);
}
/// <summary>
/// Returns a read-only list of human-readable names of
/// required fields missing from this message. Each name
@ -92,6 +88,19 @@ namespace Google.ProtocolBuffers {
return description.ToString();
}
/// <summary>
/// For Lite exceptions that do not known how to enumerate missing fields
/// </summary>
public UninitializedMessageException(IMessageLite message)
: base(String.Format("Message {0} is missing required fields", message.GetType())) {
missingFields = new List<string>();
}
#if !LITE
public UninitializedMessageException(IMessage message)
: this(FindMissingFields(message)) {
}
/// <summary>
/// Returns a list of the full "paths" of missing required
/// fields in the specified message.
@ -120,11 +129,19 @@ namespace Google.ProtocolBuffers {
if (field.IsRepeated) {
int i = 0;
foreach (object element in (IEnumerable) value) {
FindMissingFields((IMessage) element, SubMessagePrefix(prefix, field, i++), results);
if (element is IMessage) {
FindMissingFields((IMessage)element, SubMessagePrefix(prefix, field, i++), results);
} else {
results.Add(prefix + field.Name);
}
}
} else {
if (message.HasField(field)) {
FindMissingFields((IMessage) value, SubMessagePrefix(prefix, field, -1), results);
if (value is IMessage) {
FindMissingFields((IMessage)value, SubMessagePrefix(prefix, field, -1), results);
} else {
results.Add(prefix + field.Name);
}
}
}
}
@ -148,5 +165,6 @@ namespace Google.ProtocolBuffers {
result.Append('.');
return result.ToString();
}
#endif
}
}

@ -172,7 +172,9 @@ namespace Google.ProtocolBuffers {
output.WriteBytes(fieldNumber, value);
}
foreach (UnknownFieldSet value in groupList) {
#pragma warning disable 0612
output.WriteUnknownGroup(fieldNumber, value);
#pragma warning restore 0612
}
}
@ -195,7 +197,9 @@ namespace Google.ProtocolBuffers {
result += CodedOutputStream.ComputeBytesSize(fieldNumber, value);
}
foreach (UnknownFieldSet value in groupList) {
#pragma warning disable 0612
result += CodedOutputStream.ComputeUnknownGroupSize(fieldNumber, value);
#pragma warning restore 0612
}
return result;
}

@ -51,7 +51,7 @@ namespace Google.ProtocolBuffers {
///
/// Most users will never need to use this class directly.
/// </summary>
public sealed class UnknownFieldSet {
public sealed class UnknownFieldSet : IMessageLite {
private static readonly UnknownFieldSet defaultInstance = new UnknownFieldSet(new Dictionary<int, UnknownField>());
@ -138,6 +138,14 @@ namespace Google.ProtocolBuffers {
return TextFormat.PrintToString(this);
}
/// <summary>
/// Converts the set to a string in protocol buffer text format. This
/// is just a trivial wrapper around TextFormat.PrintToString.
/// </summary>
public void PrintTo(TextWriter writer) {
TextFormat.Print(this, writer);
}
/// <summary>
/// Serializes the message to a ByteString and returns it. This is
/// just a trivial wrapper around WriteTo(CodedOutputStream).
@ -237,16 +245,43 @@ namespace Google.ProtocolBuffers {
return CreateBuilder().MergeFrom(input).Build();
}
#region IMessageLite Members
public bool IsInitialized {
get { return fields != null; }
}
public void WriteDelimitedTo(Stream output) {
CodedOutputStream codedOutput = CodedOutputStream.CreateInstance(output);
codedOutput.WriteRawVarint32((uint) SerializedSize);
WriteTo(codedOutput);
codedOutput.Flush();
}
public IBuilderLite WeakCreateBuilderForType() {
return new Builder();
}
public IBuilderLite WeakToBuilder() {
return new Builder(fields);
}
public IMessageLite WeakDefaultInstanceForType {
get { return defaultInstance; }
}
#endregion
/// <summary>
/// Builder for UnknownFieldSets.
/// </summary>
public sealed class Builder
public sealed class Builder : IBuilderLite
{
/// <summary>
/// Mapping from number to field. Note that by using a SortedList we ensure
/// that the fields will be serialized in ascending order.
/// </summary>
private IDictionary<int, UnknownField> fields = new SortedList<int, UnknownField>();
private IDictionary<int, UnknownField> fields;
// Optimization: We keep around a builder for the last field that was
// modified so that we can efficiently add to it multiple times in a
// row (important when parsing an unknown repeated field).
@ -254,6 +289,11 @@ namespace Google.ProtocolBuffers {
private UnknownField.Builder lastField;
internal Builder() {
fields = new SortedList<int, UnknownField>();
}
internal Builder(IDictionary<int, UnknownField> dictionary) {
fields = new SortedList<int, UnknownField>(dictionary);
}
/// <summary>
@ -356,7 +396,9 @@ namespace Google.ProtocolBuffers {
return true;
case WireFormat.WireType.StartGroup: {
Builder subBuilder = CreateBuilder();
#pragma warning disable 0612
input.ReadUnknownGroup(number, subBuilder);
#pragma warning restore 0612
GetFieldBuilder(number).AddGroup(subBuilder.Build());
return true;
}
@ -469,6 +511,7 @@ namespace Google.ProtocolBuffers {
if (tag == 0) {
break;
}
if (!MergeFieldFrom(input, extensionRegistry, builder, tag)) {
// end group tag
break;
@ -485,7 +528,7 @@ namespace Google.ProtocolBuffers {
/// <param name="builder">Builder to merge field into, if it's a known field</param>
/// <param name="tag">The tag, which should already have been read from the input</param>
/// <returns>true unless the tag is an end-group tag</returns>
internal bool MergeFieldFrom(CodedInputStream input,
internal bool MergeFieldFrom(CodedInputStream input,
ExtensionRegistry extensionRegistry, IBuilder builder, uint tag) {
MessageDescriptor type = builder.DescriptorForType;
@ -498,7 +541,7 @@ namespace Google.ProtocolBuffers {
int fieldNumber = WireFormat.GetTagFieldNumber(tag);
FieldDescriptor field;
IMessage defaultFieldInstance = null;
IMessageLite defaultFieldInstance = null;
if (type.IsExtensionNumber(fieldNumber)) {
ExtensionInfo extension = extensionRegistry[type, fieldNumber];
@ -543,14 +586,14 @@ namespace Google.ProtocolBuffers {
switch (field.FieldType) {
case FieldType.Group:
case FieldType.Message: {
IBuilder subBuilder;
IBuilderLite subBuilder;
if (defaultFieldInstance != null) {
subBuilder = defaultFieldInstance.WeakCreateBuilderForType();
} else {
subBuilder = builder.CreateBuilderForField(field);
}
if (!field.IsRepeated) {
subBuilder.WeakMergeFrom((IMessage)builder[field]);
subBuilder.WeakMergeFrom((IMessageLite)builder[field]);
}
if (field.FieldType == FieldType.Group) {
input.ReadGroup(field.FieldNumber, subBuilder, extensionRegistry);
@ -609,7 +652,7 @@ namespace Google.ProtocolBuffers {
int typeId = 0;
ByteString rawBytes = null; // If we encounter "message" before "typeId"
IBuilder subBuilder = null;
IBuilderLite subBuilder = null;
FieldDescriptor field = null;
while (true) {
@ -626,7 +669,7 @@ namespace Google.ProtocolBuffers {
if (extension != null) {
field = extension.Descriptor;
subBuilder = extension.DefaultInstance.WeakCreateBuilderForType();
IMessage originalMessage = (IMessage)builder[field];
IMessageLite originalMessage = (IMessageLite)builder[field];
if (originalMessage != null) {
subBuilder.WeakMergeFrom(originalMessage);
}
@ -672,6 +715,54 @@ namespace Google.ProtocolBuffers {
builder[field] = subBuilder.WeakBuild();
}
}
#region IBuilderLite Members
bool IBuilderLite.IsInitialized {
get { return fields != null; }
}
IBuilderLite IBuilderLite.WeakClear() {
return Clear();
}
IBuilderLite IBuilderLite.WeakMergeFrom(IMessageLite message) {
return MergeFrom((UnknownFieldSet)message);
}
IBuilderLite IBuilderLite.WeakMergeFrom(ByteString data) {
return MergeFrom(data);
}
IBuilderLite IBuilderLite.WeakMergeFrom(ByteString data, ExtensionRegistry registry) {
return MergeFrom(data);
}
IBuilderLite IBuilderLite.WeakMergeFrom(CodedInputStream input) {
return MergeFrom(input);
}
IBuilderLite IBuilderLite.WeakMergeFrom(CodedInputStream input, ExtensionRegistry registry) {
return MergeFrom(input);
}
IMessageLite IBuilderLite.WeakBuild() {
return Build();
}
IMessageLite IBuilderLite.WeakBuildPartial() {
return Build();
}
IBuilderLite IBuilderLite.WeakClone() {
return Build().WeakToBuilder();
}
IMessageLite IBuilderLite.WeakDefaultInstanceForType {
get { return DefaultInstance; }
}
#endregion
}
}
}

@ -33,7 +33,9 @@
#endregion
using System;
#if !LITE
using Google.ProtocolBuffers.Descriptors;
#endif
namespace Google.ProtocolBuffers {
@ -115,6 +117,7 @@ namespace Google.ProtocolBuffers {
return (uint) (fieldNumber << TagTypeBits) | (uint) wireType;
}
#if !LITE
[CLSCompliant(false)]
public static uint MakeTag(FieldDescriptor field) {
return MakeTag(field.FieldNumber, GetWireType(field));
@ -170,5 +173,6 @@ namespace Google.ProtocolBuffers {
throw new ArgumentOutOfRangeException("No such field type");
}
}
#endif
}
}

@ -0,0 +1,268 @@
#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;
using Google.ProtocolBuffers.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers {
[TestFixture]
public class AbstractBuilderLiteTest {
[Test]
public void TestMergeFromCodedInputStream() {
TestAllTypesLite copy, msg = TestAllTypesLite.CreateBuilder()
.SetOptionalUint32(uint.MaxValue).Build();
copy = TestAllTypesLite.DefaultInstance;
Assert.AreNotEqual(msg.ToByteArray(), copy.ToByteArray());
using (MemoryStream ms = new MemoryStream(msg.ToByteArray())) {
CodedInputStream ci = CodedInputStream.CreateInstance(ms);
copy = copy.ToBuilder().MergeFrom(ci).Build();
}
Assert.AreEqual(msg.ToByteArray(), copy.ToByteArray());
}
[Test]
public void TestIBuilderLiteWeakClear() {
TestAllTypesLite copy, msg = TestAllTypesLite.DefaultInstance;
copy = msg.ToBuilder().SetOptionalString("Should be removed.").Build();
Assert.AreNotEqual(msg.ToByteArray(), copy.ToByteArray());
copy = (TestAllTypesLite)((IBuilderLite)copy.ToBuilder()).WeakClear().WeakBuild();
Assert.AreEqual(msg.ToByteArray(), copy.ToByteArray());
}
[Test]
public void TestBuilderLiteMergeFromCodedInputStream() {
TestAllTypesLite copy, msg = TestAllTypesLite.CreateBuilder()
.SetOptionalString("Should be merged.").Build();
copy = TestAllTypesLite.DefaultInstance;
Assert.AreNotEqual(msg.ToByteArray(), copy.ToByteArray());
copy = copy.ToBuilder().MergeFrom(CodedInputStream.CreateInstance(new MemoryStream(msg.ToByteArray()))).Build();
Assert.AreEqual(msg.ToByteArray(), copy.ToByteArray());
}
[Test]
public void TestBuilderLiteMergeDelimitedFrom() {
TestAllTypesLite copy, msg = TestAllTypesLite.CreateBuilder()
.SetOptionalString("Should be merged.").Build();
copy = TestAllTypesLite.DefaultInstance;
Assert.AreNotEqual(msg.ToByteArray(), copy.ToByteArray());
Stream s = new MemoryStream();
msg.WriteDelimitedTo(s);
s.Position = 0;
copy = copy.ToBuilder().MergeDelimitedFrom(s).Build();
Assert.AreEqual(msg.ToByteArray(), copy.ToByteArray());
}
[Test]
public void TestBuilderLiteMergeDelimitedFromExtensions() {
TestAllExtensionsLite copy, msg = TestAllExtensionsLite.CreateBuilder()
.SetExtension(UnitTestLiteProtoFile.OptionalStringExtensionLite, "Should be merged.").Build();
copy = TestAllExtensionsLite.DefaultInstance;
Assert.AreNotEqual(msg.ToByteArray(), copy.ToByteArray());
Stream s = new MemoryStream();
msg.WriteDelimitedTo(s);
s.Position = 0;
ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
UnitTestLiteProtoFile.RegisterAllExtensions(registry);
copy = copy.ToBuilder().MergeDelimitedFrom(s, registry).Build();
Assert.AreEqual(msg.ToByteArray(), copy.ToByteArray());
Assert.AreEqual("Should be merged.", copy.GetExtension(UnitTestLiteProtoFile.OptionalStringExtensionLite));
}
[Test]
public void TestBuilderLiteMergeFromStream() {
TestAllTypesLite copy, msg = TestAllTypesLite.CreateBuilder()
.SetOptionalString("Should be merged.").Build();
copy = TestAllTypesLite.DefaultInstance;
Assert.AreNotEqual(msg.ToByteArray(), copy.ToByteArray());
Stream s = new MemoryStream();
msg.WriteTo(s);
s.Position = 0;
copy = copy.ToBuilder().MergeFrom(s).Build();
Assert.AreEqual(msg.ToByteArray(), copy.ToByteArray());
}
[Test]
public void TestBuilderLiteMergeFromStreamExtensions() {
TestAllExtensionsLite copy, msg = TestAllExtensionsLite.CreateBuilder()
.SetExtension(UnitTestLiteProtoFile.OptionalStringExtensionLite, "Should be merged.").Build();
copy = TestAllExtensionsLite.DefaultInstance;
Assert.AreNotEqual(msg.ToByteArray(), copy.ToByteArray());
Stream s = new MemoryStream();
msg.WriteTo(s);
s.Position = 0;
ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
UnitTestLiteProtoFile.RegisterAllExtensions(registry);
copy = copy.ToBuilder().MergeFrom(s, registry).Build();
Assert.AreEqual(msg.ToByteArray(), copy.ToByteArray());
Assert.AreEqual("Should be merged.", copy.GetExtension(UnitTestLiteProtoFile.OptionalStringExtensionLite));
}
[Test]
public void TestIBuilderLiteWeakMergeFromIMessageLite() {
TestAllTypesLite copy, msg = TestAllTypesLite.CreateBuilder()
.SetOptionalString("Should be merged.").Build();
copy = TestAllTypesLite.DefaultInstance;
Assert.AreNotEqual(msg.ToByteArray(), copy.ToByteArray());
copy = (TestAllTypesLite)((IBuilderLite)copy.ToBuilder()).WeakMergeFrom((IMessageLite)msg).WeakBuild();
Assert.AreEqual(msg.ToByteArray(), copy.ToByteArray());
}
[Test]
public void TestIBuilderLiteWeakMergeFromByteString() {
TestAllTypesLite copy, msg = TestAllTypesLite.CreateBuilder()
.SetOptionalString("Should be merged.").Build();
copy = TestAllTypesLite.DefaultInstance;
Assert.AreNotEqual(msg.ToByteArray(), copy.ToByteArray());
copy = (TestAllTypesLite)((IBuilderLite)copy.ToBuilder()).WeakMergeFrom(msg.ToByteString()).WeakBuild();
Assert.AreEqual(msg.ToByteArray(), copy.ToByteArray());
}
[Test]
public void TestIBuilderLiteWeakMergeFromByteStringExtensions() {
TestAllExtensionsLite copy, msg = TestAllExtensionsLite.CreateBuilder()
.SetExtension(UnitTestLiteProtoFile.OptionalStringExtensionLite, "Should be merged.").Build();
copy = TestAllExtensionsLite.DefaultInstance;
Assert.AreNotEqual(msg.ToByteArray(), copy.ToByteArray());
copy = (TestAllExtensionsLite)((IBuilderLite)copy.ToBuilder()).WeakMergeFrom(msg.ToByteString(), ExtensionRegistry.Empty).WeakBuild();
Assert.AreNotEqual(msg.ToByteArray(), copy.ToByteArray());
ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
UnitTestLiteProtoFile.RegisterAllExtensions(registry);
copy = (TestAllExtensionsLite)((IBuilderLite)copy.ToBuilder()).WeakMergeFrom(msg.ToByteString(), registry).WeakBuild();
Assert.AreEqual(msg.ToByteArray(), copy.ToByteArray());
Assert.AreEqual("Should be merged.", copy.GetExtension(UnitTestLiteProtoFile.OptionalStringExtensionLite));
}
[Test]
public void TestIBuilderLiteWeakMergeFromCodedInputStream() {
TestAllTypesLite copy, msg = TestAllTypesLite.CreateBuilder()
.SetOptionalUint32(uint.MaxValue).Build();
copy = TestAllTypesLite.DefaultInstance;
Assert.AreNotEqual(msg.ToByteArray(), copy.ToByteArray());
using (MemoryStream ms = new MemoryStream(msg.ToByteArray())) {
CodedInputStream ci = CodedInputStream.CreateInstance(ms);
copy = (TestAllTypesLite)((IBuilderLite)copy.ToBuilder()).WeakMergeFrom(ci).WeakBuild();
}
Assert.AreEqual(msg.ToByteArray(), copy.ToByteArray());
}
[Test]
public void TestIBuilderLiteWeakBuildPartial() {
IBuilderLite builder = TestRequiredLite.CreateBuilder();
Assert.IsFalse(builder.IsInitialized);
IMessageLite msg = builder.WeakBuildPartial();
Assert.IsFalse(msg.IsInitialized);
Assert.AreEqual(msg.ToByteArray(), TestRequiredLite.DefaultInstance.ToByteArray());
}
[Test, ExpectedException(typeof(UninitializedMessageException ))]
public void TestIBuilderLiteWeakBuildUninitialized() {
IBuilderLite builder = TestRequiredLite.CreateBuilder();
Assert.IsFalse(builder.IsInitialized);
builder.WeakBuild();
}
[Test]
public void TestIBuilderLiteWeakBuild() {
IBuilderLite builder = TestRequiredLite.CreateBuilder()
.SetD(0)
.SetEn(ExtraEnum.EXLITE_BAZ);
Assert.IsTrue(builder.IsInitialized);
builder.WeakBuild();
}
[Test]
public void TestIBuilderLiteWeakClone() {
TestRequiredLite msg = TestRequiredLite.CreateBuilder()
.SetD(1).SetEn(ExtraEnum.EXLITE_BAR).Build();
Assert.IsTrue(msg.IsInitialized);
IMessageLite copy = ((IBuilderLite)msg.ToBuilder()).WeakClone().WeakBuild();
Assert.AreEqual(msg.ToByteArray(), copy.ToByteArray());
}
[Test]
public void TestIBuilderLiteWeakDefaultInstance() {
Assert.IsTrue(ReferenceEquals(TestRequiredLite.DefaultInstance,
((IBuilderLite)TestRequiredLite.CreateBuilder()).WeakDefaultInstanceForType));
}
[Test]
public void TestGeneratedBuilderLiteAddRange() {
TestAllTypesLite copy, msg = TestAllTypesLite.CreateBuilder()
.SetOptionalUint32(123)
.AddRepeatedInt32(1)
.AddRepeatedInt32(2)
.AddRepeatedInt32(3)
.Build();
copy = msg.DefaultInstanceForType.ToBuilder().MergeFrom(msg).Build();
Assert.AreEqual(msg.ToByteArray(), copy.ToByteArray());
}
}
}

@ -0,0 +1,126 @@
#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;
using Google.ProtocolBuffers.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers {
[TestFixture]
public class AbstractMessageLiteTest {
[Test]
public void TestMessageLiteToByteString() {
TestRequiredLite msg = TestRequiredLite.CreateBuilder()
.SetD(42)
.SetEn(ExtraEnum.EXLITE_BAZ)
.Build();
ByteString b = msg.ToByteString();
Assert.AreEqual(4, b.Length);
Assert.AreEqual(TestRequiredLite.DFieldNumber << 3, b[0]);
Assert.AreEqual(42, b[1]);
Assert.AreEqual(TestRequiredLite.EnFieldNumber << 3, b[2]);
Assert.AreEqual((int)ExtraEnum.EXLITE_BAZ, b[3]);
}
[Test]
public void TestMessageLiteToByteArray() {
TestRequiredLite msg = TestRequiredLite.CreateBuilder()
.SetD(42)
.SetEn(ExtraEnum.EXLITE_BAZ)
.Build();
ByteString b = msg.ToByteString();
ByteString copy = ByteString.CopyFrom(msg.ToByteArray());
Assert.AreEqual(b, copy);
}
[Test]
public void TestMessageLiteWriteTo() {
TestRequiredLite msg = TestRequiredLite.CreateBuilder()
.SetD(42)
.SetEn(ExtraEnum.EXLITE_BAZ)
.Build();
MemoryStream ms = new MemoryStream();
msg.WriteTo(ms);
Assert.AreEqual(msg.ToByteArray(), ms.ToArray());
}
[Test]
public void TestMessageLiteWriteDelimitedTo() {
TestRequiredLite msg = TestRequiredLite.CreateBuilder()
.SetD(42)
.SetEn(ExtraEnum.EXLITE_BAZ)
.Build();
MemoryStream ms = new MemoryStream();
msg.WriteDelimitedTo(ms);
byte[] buffer = ms.ToArray();
Assert.AreEqual(5, buffer.Length);
Assert.AreEqual(4, buffer[0]);
byte[] msgBytes = new byte[4];
Array.Copy(buffer, 1, msgBytes, 0, 4);
Assert.AreEqual(msg.ToByteArray(), msgBytes);
}
[Test]
public void TestIMessageLiteWeakCreateBuilderForType() {
IMessageLite msg = TestRequiredLite.DefaultInstance;
Assert.AreEqual(typeof(TestRequiredLite.Builder), msg.WeakCreateBuilderForType().GetType());
}
[Test]
public void TestMessageLiteWeakToBuilder() {
IMessageLite msg = TestRequiredLite.CreateBuilder()
.SetD(42)
.SetEn(ExtraEnum.EXLITE_BAZ)
.Build();
IMessageLite copy = msg.WeakToBuilder().WeakBuild();
Assert.AreEqual(msg.ToByteArray(), copy.ToByteArray());
}
[Test]
public void TestMessageLiteWeakDefaultInstanceForType() {
IMessageLite msg = TestRequiredLite.DefaultInstance;
Assert.IsTrue(Object.ReferenceEquals(TestRequiredLite.DefaultInstance, msg.WeakDefaultInstanceForType));
}
}
}

@ -0,0 +1,267 @@
#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;
using Google.ProtocolBuffers.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers {
[TestFixture]
public class ExtendableBuilderLiteTest {
[Test]
public void TestHasExtensionT() {
TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.CreateBuilder()
.SetExtension(UnitTestLiteProtoFile.OptionalInt32ExtensionLite, 123);
Assert.IsTrue(builder.HasExtension(UnitTestLiteProtoFile.OptionalInt32ExtensionLite));
}
[Test]
public void TestHasExtensionTMissing() {
TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.CreateBuilder();
Assert.IsFalse(builder.HasExtension(UnitTestLiteProtoFile.OptionalInt32ExtensionLite));
}
[Test]
public void TestGetExtensionCountT() {
TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.CreateBuilder()
.AddExtension(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite, 1)
.AddExtension(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite, 2)
.AddExtension(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite, 3);
Assert.AreEqual(3, builder.GetExtensionCount(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite));
}
[Test]
public void TestGetExtensionCountTEmpty() {
TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.CreateBuilder();
Assert.AreEqual(0, builder.GetExtensionCount(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite));
}
[Test]
public void TestGetExtensionTNull() {
TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.CreateBuilder();
string value = builder.GetExtension(UnitTestLiteProtoFile.OptionalStringExtensionLite);
Assert.IsNull(value);
}
[Test]
public void TestGetExtensionTValue() {
TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.CreateBuilder()
.SetExtension(UnitTestLiteProtoFile.OptionalInt32ExtensionLite, 3);
Assert.AreEqual(3, builder.GetExtension(UnitTestLiteProtoFile.OptionalInt32ExtensionLite));
}
[Test]
public void TestGetExtensionTEmpty() {
TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.CreateBuilder();
Assert.AreEqual(0, builder.GetExtension(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite).Count);
}
[Test]
public void TestGetExtensionTList() {
TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.CreateBuilder()
.AddExtension(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite, 1)
.AddExtension(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite, 2)
.AddExtension(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite, 3);
IList<int> values = builder.GetExtension(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite);
Assert.AreEqual(3, values.Count);
}
[Test]
public void TestGetExtensionTIndex() {
TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.CreateBuilder()
.AddExtension(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite, 0)
.AddExtension(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite, 1)
.AddExtension(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite, 2);
for(int i = 0; i < 3; i++ )
Assert.AreEqual(i, builder.GetExtension(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite, i));
}
[Test,ExpectedException(typeof(ArgumentOutOfRangeException))]
public void TestGetExtensionTIndexOutOfRange() {
TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.CreateBuilder();
builder.GetExtension(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite, 0);
}
[Test]
public void TestSetExtensionTIndex() {
TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.CreateBuilder()
.AddExtension(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite, 0)
.AddExtension(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite, 1)
.AddExtension(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite, 2);
for (int i = 0; i < 3; i++)
Assert.AreEqual(i, builder.GetExtension(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite, i));
builder.SetExtension(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite, 0, 5);
builder.SetExtension(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite, 1, 6);
builder.SetExtension(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite, 2, 7);
for (int i = 0; i < 3; i++)
Assert.AreEqual(5 + i, builder.GetExtension(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite, i));
}
[Test, ExpectedException(typeof(ArgumentOutOfRangeException))]
public void TestSetExtensionTIndexOutOfRange() {
TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.CreateBuilder();
builder.SetExtension(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite, 0, -1);
}
[Test]
public void TestClearExtensionTList() {
TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.CreateBuilder()
.AddExtension(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite, 0);
Assert.AreEqual(1, builder.GetExtensionCount(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite));
builder.ClearExtension(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite);
Assert.AreEqual(0, builder.GetExtensionCount(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite));
}
[Test]
public void TestClearExtensionTValue() {
TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.CreateBuilder()
.SetExtension(UnitTestLiteProtoFile.OptionalInt32ExtensionLite, 0);
Assert.IsTrue(builder.HasExtension(UnitTestLiteProtoFile.OptionalInt32ExtensionLite));
builder.ClearExtension(UnitTestLiteProtoFile.OptionalInt32ExtensionLite);
Assert.IsFalse(builder.HasExtension(UnitTestLiteProtoFile.OptionalInt32ExtensionLite));
}
[Test]
public void TestIndexedByDescriptor() {
TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.CreateBuilder();
Assert.IsFalse(builder.HasExtension(UnitTestLiteProtoFile.OptionalInt32ExtensionLite));
builder[UnitTestLiteProtoFile.OptionalInt32ExtensionLite.Descriptor] = 123;
Assert.IsTrue(builder.HasExtension(UnitTestLiteProtoFile.OptionalInt32ExtensionLite));
Assert.AreEqual(123, builder.GetExtension(UnitTestLiteProtoFile.OptionalInt32ExtensionLite));
}
[Test]
public void TestIndexedByDescriptorAndOrdinal() {
TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.CreateBuilder()
.AddExtension(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite, 0);
Assert.AreEqual(1, builder.GetExtensionCount(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite));
IFieldDescriptorLite f = UnitTestLiteProtoFile.RepeatedInt32ExtensionLite.Descriptor;
builder[f, 0] = 123;
Assert.AreEqual(1, builder.GetExtensionCount(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite));
Assert.AreEqual(123, builder.GetExtension(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite, 0));
}
[Test, ExpectedException(typeof(ArgumentOutOfRangeException))]
public void TestIndexedByDescriptorAndOrdinalOutOfRange() {
TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.CreateBuilder();
Assert.AreEqual(0, builder.GetExtensionCount(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite));
IFieldDescriptorLite f = UnitTestLiteProtoFile.RepeatedInt32ExtensionLite.Descriptor;
builder[f, 0] = 123;
}
[Test]
public void TestClearFieldByDescriptor() {
TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.CreateBuilder()
.AddExtension(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite, 0);
Assert.AreEqual(1, builder.GetExtensionCount(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite));
IFieldDescriptorLite f = UnitTestLiteProtoFile.RepeatedInt32ExtensionLite.Descriptor;
builder.ClearField(f);
Assert.AreEqual(0, builder.GetExtensionCount(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite));
}
[Test]
public void TestAddRepeatedFieldByDescriptor() {
TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.CreateBuilder()
.AddExtension(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite, 0);
Assert.AreEqual(1, builder.GetExtensionCount(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite));
IFieldDescriptorLite f = UnitTestLiteProtoFile.RepeatedInt32ExtensionLite.Descriptor;
builder.AddRepeatedField(f, 123);
Assert.AreEqual(2, builder.GetExtensionCount(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite));
Assert.AreEqual(123, builder.GetExtension(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite, 1));
}
[Test]
public void TestMissingExtensionsLite()
{
const int optionalInt32 = 12345678;
TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.CreateBuilder();
builder.SetExtension(UnitTestLiteProtoFile.OptionalInt32ExtensionLite, optionalInt32);
builder.AddExtension(UnitTestLiteProtoFile.RepeatedDoubleExtensionLite, 1.1);
builder.AddExtension(UnitTestLiteProtoFile.RepeatedDoubleExtensionLite, 1.2);
builder.AddExtension(UnitTestLiteProtoFile.RepeatedDoubleExtensionLite, 1.3);
TestAllExtensionsLite msg = builder.Build();
Assert.IsTrue(msg.HasExtension(UnitTestLiteProtoFile.OptionalInt32ExtensionLite));
Assert.AreEqual(3, msg.GetExtensionCount(UnitTestLiteProtoFile.RepeatedDoubleExtensionLite));
byte[] bits = msg.ToByteArray();
TestAllExtensionsLite copy = TestAllExtensionsLite.ParseFrom(bits);
Assert.IsFalse(copy.HasExtension(UnitTestLiteProtoFile.OptionalInt32ExtensionLite));
Assert.AreEqual(0, copy.GetExtensionCount(UnitTestLiteProtoFile.RepeatedDoubleExtensionLite));
Assert.AreNotEqual(msg, copy);
//The lite runtime removes all unknown fields and extensions
byte[] copybits = copy.ToByteArray();
Assert.AreEqual(0, copybits.Length);
}
[Test]
public void TestMissingFieldsLite()
{
TestAllTypesLite msg = TestAllTypesLite.CreateBuilder()
.SetOptionalInt32(123)
.SetOptionalString("123")
.Build();
byte[] bits = msg.ToByteArray();
TestAllExtensionsLite copy = TestAllExtensionsLite.ParseFrom(bits);
Assert.AreNotEqual(msg, copy);
//The lite runtime removes all unknown fields and extensions
byte[] copybits = copy.ToByteArray();
Assert.AreEqual(0, copybits.Length);
}
}
}

@ -0,0 +1,304 @@
#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.Text;
using Google.ProtocolBuffers;
using Google.ProtocolBuffers.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers {
[TestFixture]
public class ExtendableMessageLiteTest {
[Test, Ignore("Not implemented, no assertion made"), ExpectedException(typeof(ArgumentException))]
public void ExtensionWriterInvalidExtension() {
TestPackedExtensionsLite.CreateBuilder()[UnitTestLiteProtoFile.OptionalForeignMessageExtensionLite.Descriptor] =
ForeignMessageLite.DefaultInstance;
}
[Test]
public void ExtensionWriterTestMessages() {
TestAllExtensionsLite.Builder b = TestAllExtensionsLite.CreateBuilder().SetExtension(
UnitTestLiteProtoFile.OptionalForeignMessageExtensionLite, ForeignMessageLite.CreateBuilder().SetC(123).Build());
TestAllExtensionsLite copy, msg = b.Build();
ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
UnitTestLiteProtoFile.RegisterAllExtensions(registry);
copy = TestAllExtensionsLite.ParseFrom(msg.ToByteArray(), registry);
Assert.AreEqual(msg.ToByteArray(), copy.ToByteArray());
}
[Test]
public void ExtensionWriterIsInitialized() {
Assert.IsTrue(ForeignMessageLite.DefaultInstance.IsInitialized);
Assert.IsTrue(TestPackedExtensionsLite.CreateBuilder().IsInitialized);
Assert.IsTrue(TestAllExtensionsLite.CreateBuilder().SetExtension(
UnitTestLiteProtoFile.OptionalForeignMessageExtensionLite, ForeignMessageLite.DefaultInstance)
.IsInitialized);
}
[Test]
public void ExtensionWriterTestSetExtensionLists() {
TestAllExtensionsLite msg, copy;
TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.CreateBuilder()
.SetExtension(UnitTestLiteProtoFile.RepeatedBoolExtensionLite, new[] { true, false })
.SetExtension(UnitTestLiteProtoFile.RepeatedCordExtensionLite, new[] { "123", "456" })
.SetExtension(UnitTestLiteProtoFile.RepeatedForeignEnumExtensionLite, new[] { ForeignEnumLite.FOREIGN_LITE_BAZ, ForeignEnumLite.FOREIGN_LITE_FOO })
;
msg = builder.Build();
ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
UnitTestLiteProtoFile.RegisterAllExtensions(registry);
copy = TestAllExtensionsLite.ParseFrom(msg.ToByteArray(), registry);
Assert.AreEqual(msg.ToByteArray(), copy.ToByteArray());
Assert.AreEqual(ForeignEnumLite.FOREIGN_LITE_FOO, copy.GetExtension(UnitTestLiteProtoFile.RepeatedForeignEnumExtensionLite, 1));
}
[Test]
public void ExtensionWriterTest() {
TestAllExtensionsLite.Builder builder = TestAllExtensionsLite.CreateBuilder()
.SetExtension(UnitTestLiteProtoFile.DefaultBoolExtensionLite, true)
.SetExtension(UnitTestLiteProtoFile.DefaultBytesExtensionLite, ByteString.CopyFromUtf8("123"))
.SetExtension(UnitTestLiteProtoFile.DefaultCordExtensionLite, "123")
.SetExtension(UnitTestLiteProtoFile.DefaultDoubleExtensionLite, 123)
.SetExtension(UnitTestLiteProtoFile.DefaultFixed32ExtensionLite, 123u)
.SetExtension(UnitTestLiteProtoFile.DefaultFixed64ExtensionLite, 123u)
.SetExtension(UnitTestLiteProtoFile.DefaultFloatExtensionLite, 123)
.SetExtension(UnitTestLiteProtoFile.DefaultForeignEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_BAZ)
.SetExtension(UnitTestLiteProtoFile.DefaultImportEnumExtensionLite, ImportEnumLite.IMPORT_LITE_BAZ)
.SetExtension(UnitTestLiteProtoFile.DefaultInt32ExtensionLite, 123)
.SetExtension(UnitTestLiteProtoFile.DefaultInt64ExtensionLite, 123)
.SetExtension(UnitTestLiteProtoFile.DefaultNestedEnumExtensionLite, TestAllTypesLite.Types.NestedEnum.FOO)
.SetExtension(UnitTestLiteProtoFile.DefaultSfixed32ExtensionLite, 123)
.SetExtension(UnitTestLiteProtoFile.DefaultSfixed64ExtensionLite, 123)
.SetExtension(UnitTestLiteProtoFile.DefaultSint32ExtensionLite, 123)
.SetExtension(UnitTestLiteProtoFile.DefaultSint64ExtensionLite, 123)
.SetExtension(UnitTestLiteProtoFile.DefaultStringExtensionLite, "123")
.SetExtension(UnitTestLiteProtoFile.DefaultStringPieceExtensionLite, "123")
.SetExtension(UnitTestLiteProtoFile.DefaultUint32ExtensionLite, 123u)
.SetExtension(UnitTestLiteProtoFile.DefaultUint64ExtensionLite, 123u)
//Optional
.SetExtension(UnitTestLiteProtoFile.OptionalBoolExtensionLite, true)
.SetExtension(UnitTestLiteProtoFile.OptionalBytesExtensionLite, ByteString.CopyFromUtf8("123"))
.SetExtension(UnitTestLiteProtoFile.OptionalCordExtensionLite, "123")
.SetExtension(UnitTestLiteProtoFile.OptionalDoubleExtensionLite, 123)
.SetExtension(UnitTestLiteProtoFile.OptionalFixed32ExtensionLite, 123u)
.SetExtension(UnitTestLiteProtoFile.OptionalFixed64ExtensionLite, 123u)
.SetExtension(UnitTestLiteProtoFile.OptionalFloatExtensionLite, 123)
.SetExtension(UnitTestLiteProtoFile.OptionalForeignEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_BAZ)
.SetExtension(UnitTestLiteProtoFile.OptionalImportEnumExtensionLite, ImportEnumLite.IMPORT_LITE_BAZ)
.SetExtension(UnitTestLiteProtoFile.OptionalInt32ExtensionLite, 123)
.SetExtension(UnitTestLiteProtoFile.OptionalInt64ExtensionLite, 123)
.SetExtension(UnitTestLiteProtoFile.OptionalNestedEnumExtensionLite, TestAllTypesLite.Types.NestedEnum.FOO)
.SetExtension(UnitTestLiteProtoFile.OptionalSfixed32ExtensionLite, 123)
.SetExtension(UnitTestLiteProtoFile.OptionalSfixed64ExtensionLite, 123)
.SetExtension(UnitTestLiteProtoFile.OptionalSint32ExtensionLite, 123)
.SetExtension(UnitTestLiteProtoFile.OptionalSint64ExtensionLite, 123)
.SetExtension(UnitTestLiteProtoFile.OptionalStringExtensionLite, "123")
.SetExtension(UnitTestLiteProtoFile.OptionalStringPieceExtensionLite, "123")
.SetExtension(UnitTestLiteProtoFile.OptionalUint32ExtensionLite, 123u)
.SetExtension(UnitTestLiteProtoFile.OptionalUint64ExtensionLite, 123u)
//Repeated
.AddExtension(UnitTestLiteProtoFile.RepeatedBoolExtensionLite, true)
.AddExtension(UnitTestLiteProtoFile.RepeatedBytesExtensionLite, ByteString.CopyFromUtf8("123"))
.AddExtension(UnitTestLiteProtoFile.RepeatedCordExtensionLite, "123")
.AddExtension(UnitTestLiteProtoFile.RepeatedDoubleExtensionLite, 123)
.AddExtension(UnitTestLiteProtoFile.RepeatedFixed32ExtensionLite, 123u)
.AddExtension(UnitTestLiteProtoFile.RepeatedFixed64ExtensionLite, 123u)
.AddExtension(UnitTestLiteProtoFile.RepeatedFloatExtensionLite, 123)
.AddExtension(UnitTestLiteProtoFile.RepeatedForeignEnumExtensionLite, ForeignEnumLite.FOREIGN_LITE_BAZ)
.AddExtension(UnitTestLiteProtoFile.RepeatedImportEnumExtensionLite, ImportEnumLite.IMPORT_LITE_BAZ)
.AddExtension(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite, 123)
.AddExtension(UnitTestLiteProtoFile.RepeatedInt64ExtensionLite, 123)
.AddExtension(UnitTestLiteProtoFile.RepeatedNestedEnumExtensionLite, TestAllTypesLite.Types.NestedEnum.FOO)
.AddExtension(UnitTestLiteProtoFile.RepeatedSfixed32ExtensionLite, 123)
.AddExtension(UnitTestLiteProtoFile.RepeatedSfixed64ExtensionLite, 123)
.AddExtension(UnitTestLiteProtoFile.RepeatedSint32ExtensionLite, 123)
.AddExtension(UnitTestLiteProtoFile.RepeatedSint64ExtensionLite, 123)
.AddExtension(UnitTestLiteProtoFile.RepeatedStringExtensionLite, "123")
.AddExtension(UnitTestLiteProtoFile.RepeatedStringPieceExtensionLite, "123")
.AddExtension(UnitTestLiteProtoFile.RepeatedUint32ExtensionLite, 123u)
.AddExtension(UnitTestLiteProtoFile.RepeatedUint64ExtensionLite, 123u)
;
TestAllExtensionsLite msg = builder.Build();
ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
UnitTestLiteProtoFile.RegisterAllExtensions(registry);
TestAllExtensionsLite.Builder copyBuilder = TestAllExtensionsLite.CreateBuilder().MergeFrom(msg.ToByteArray(), registry);
TestAllExtensionsLite copy = copyBuilder.Build();
Assert.AreEqual(msg.ToByteArray(), copy.ToByteArray());
Assert.AreEqual(true, copy.GetExtension(UnitTestLiteProtoFile.DefaultBoolExtensionLite));
Assert.AreEqual(ByteString.CopyFromUtf8("123"), copy.GetExtension(UnitTestLiteProtoFile.DefaultBytesExtensionLite));
Assert.AreEqual("123", copy.GetExtension(UnitTestLiteProtoFile.DefaultCordExtensionLite));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.DefaultDoubleExtensionLite));
Assert.AreEqual(123u, copy.GetExtension(UnitTestLiteProtoFile.DefaultFixed32ExtensionLite));
Assert.AreEqual(123u, copy.GetExtension(UnitTestLiteProtoFile.DefaultFixed64ExtensionLite));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.DefaultFloatExtensionLite));
Assert.AreEqual(ForeignEnumLite.FOREIGN_LITE_BAZ, copy.GetExtension(UnitTestLiteProtoFile.DefaultForeignEnumExtensionLite));
Assert.AreEqual(ImportEnumLite.IMPORT_LITE_BAZ, copy.GetExtension(UnitTestLiteProtoFile.DefaultImportEnumExtensionLite));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.DefaultInt32ExtensionLite));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.DefaultInt64ExtensionLite));
Assert.AreEqual(TestAllTypesLite.Types.NestedEnum.FOO, copy.GetExtension(UnitTestLiteProtoFile.DefaultNestedEnumExtensionLite));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.DefaultSfixed32ExtensionLite));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.DefaultSfixed64ExtensionLite));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.DefaultSint32ExtensionLite));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.DefaultSint64ExtensionLite));
Assert.AreEqual("123", copy.GetExtension(UnitTestLiteProtoFile.DefaultStringExtensionLite));
Assert.AreEqual("123", copy.GetExtension(UnitTestLiteProtoFile.DefaultStringPieceExtensionLite));
Assert.AreEqual(123u, copy.GetExtension(UnitTestLiteProtoFile.DefaultUint32ExtensionLite));
Assert.AreEqual(123u, copy.GetExtension(UnitTestLiteProtoFile.DefaultUint64ExtensionLite));
Assert.AreEqual(true, copy.GetExtension(UnitTestLiteProtoFile.OptionalBoolExtensionLite));
Assert.AreEqual(ByteString.CopyFromUtf8("123"), copy.GetExtension(UnitTestLiteProtoFile.OptionalBytesExtensionLite));
Assert.AreEqual("123", copy.GetExtension(UnitTestLiteProtoFile.OptionalCordExtensionLite));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.OptionalDoubleExtensionLite));
Assert.AreEqual(123u, copy.GetExtension(UnitTestLiteProtoFile.OptionalFixed32ExtensionLite));
Assert.AreEqual(123u, copy.GetExtension(UnitTestLiteProtoFile.OptionalFixed64ExtensionLite));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.OptionalFloatExtensionLite));
Assert.AreEqual(ForeignEnumLite.FOREIGN_LITE_BAZ, copy.GetExtension(UnitTestLiteProtoFile.OptionalForeignEnumExtensionLite));
Assert.AreEqual(ImportEnumLite.IMPORT_LITE_BAZ, copy.GetExtension(UnitTestLiteProtoFile.OptionalImportEnumExtensionLite));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.OptionalInt32ExtensionLite));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.OptionalInt64ExtensionLite));
Assert.AreEqual(TestAllTypesLite.Types.NestedEnum.FOO, copy.GetExtension(UnitTestLiteProtoFile.OptionalNestedEnumExtensionLite));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.OptionalSfixed32ExtensionLite));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.OptionalSfixed64ExtensionLite));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.OptionalSint32ExtensionLite));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.OptionalSint64ExtensionLite));
Assert.AreEqual("123", copy.GetExtension(UnitTestLiteProtoFile.OptionalStringExtensionLite));
Assert.AreEqual("123", copy.GetExtension(UnitTestLiteProtoFile.OptionalStringPieceExtensionLite));
Assert.AreEqual(123u, copy.GetExtension(UnitTestLiteProtoFile.OptionalUint32ExtensionLite));
Assert.AreEqual(123u, copy.GetExtension(UnitTestLiteProtoFile.OptionalUint64ExtensionLite));
Assert.AreEqual(true, copy.GetExtension(UnitTestLiteProtoFile.RepeatedBoolExtensionLite, 0));
Assert.AreEqual(ByteString.CopyFromUtf8("123"), copy.GetExtension(UnitTestLiteProtoFile.RepeatedBytesExtensionLite, 0));
Assert.AreEqual("123", copy.GetExtension(UnitTestLiteProtoFile.RepeatedCordExtensionLite, 0));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.RepeatedDoubleExtensionLite, 0));
Assert.AreEqual(123u, copy.GetExtension(UnitTestLiteProtoFile.RepeatedFixed32ExtensionLite, 0));
Assert.AreEqual(123u, copy.GetExtension(UnitTestLiteProtoFile.RepeatedFixed64ExtensionLite, 0));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.RepeatedFloatExtensionLite, 0));
Assert.AreEqual(ForeignEnumLite.FOREIGN_LITE_BAZ, copy.GetExtension(UnitTestLiteProtoFile.RepeatedForeignEnumExtensionLite, 0));
Assert.AreEqual(ImportEnumLite.IMPORT_LITE_BAZ, copy.GetExtension(UnitTestLiteProtoFile.RepeatedImportEnumExtensionLite, 0));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.RepeatedInt32ExtensionLite, 0));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.RepeatedInt64ExtensionLite, 0));
Assert.AreEqual(TestAllTypesLite.Types.NestedEnum.FOO, copy.GetExtension(UnitTestLiteProtoFile.RepeatedNestedEnumExtensionLite, 0));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.RepeatedSfixed32ExtensionLite, 0));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.RepeatedSfixed64ExtensionLite, 0));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.RepeatedSint32ExtensionLite, 0));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.RepeatedSint64ExtensionLite, 0));
Assert.AreEqual("123", copy.GetExtension(UnitTestLiteProtoFile.RepeatedStringExtensionLite, 0));
Assert.AreEqual("123", copy.GetExtension(UnitTestLiteProtoFile.RepeatedStringPieceExtensionLite, 0));
Assert.AreEqual(123u, copy.GetExtension(UnitTestLiteProtoFile.RepeatedUint32ExtensionLite, 0));
Assert.AreEqual(123u, copy.GetExtension(UnitTestLiteProtoFile.RepeatedUint64ExtensionLite, 0));
}
[Test]
public void ExtensionWriterTestPacked() {
TestPackedExtensionsLite.Builder builder = TestPackedExtensionsLite.CreateBuilder()
.AddExtension(UnitTestLiteProtoFile.PackedBoolExtensionLite, true)
.AddExtension(UnitTestLiteProtoFile.PackedDoubleExtensionLite, 123)
.AddExtension(UnitTestLiteProtoFile.PackedFixed32ExtensionLite, 123u)
.AddExtension(UnitTestLiteProtoFile.PackedFixed64ExtensionLite, 123u)
.AddExtension(UnitTestLiteProtoFile.PackedFloatExtensionLite, 123)
.AddExtension(UnitTestLiteProtoFile.PackedInt32ExtensionLite, 123)
.AddExtension(UnitTestLiteProtoFile.PackedInt64ExtensionLite, 123)
.AddExtension(UnitTestLiteProtoFile.PackedSfixed32ExtensionLite, 123)
.AddExtension(UnitTestLiteProtoFile.PackedSfixed64ExtensionLite, 123)
.AddExtension(UnitTestLiteProtoFile.PackedSint32ExtensionLite, 123)
.AddExtension(UnitTestLiteProtoFile.PackedSint64ExtensionLite, 123)
.AddExtension(UnitTestLiteProtoFile.PackedUint32ExtensionLite, 123u)
.AddExtension(UnitTestLiteProtoFile.PackedUint64ExtensionLite, 123u)
.AddExtension(UnitTestLiteProtoFile.PackedBoolExtensionLite, true)
.AddExtension(UnitTestLiteProtoFile.PackedDoubleExtensionLite, 123)
.AddExtension(UnitTestLiteProtoFile.PackedFixed32ExtensionLite, 123u)
.AddExtension(UnitTestLiteProtoFile.PackedFixed64ExtensionLite, 123u)
.AddExtension(UnitTestLiteProtoFile.PackedFloatExtensionLite, 123)
.AddExtension(UnitTestLiteProtoFile.PackedInt32ExtensionLite, 123)
.AddExtension(UnitTestLiteProtoFile.PackedInt64ExtensionLite, 123)
.AddExtension(UnitTestLiteProtoFile.PackedSfixed32ExtensionLite, 123)
.AddExtension(UnitTestLiteProtoFile.PackedSfixed64ExtensionLite, 123)
.AddExtension(UnitTestLiteProtoFile.PackedSint32ExtensionLite, 123)
.AddExtension(UnitTestLiteProtoFile.PackedSint64ExtensionLite, 123)
.AddExtension(UnitTestLiteProtoFile.PackedUint32ExtensionLite, 123u)
.AddExtension(UnitTestLiteProtoFile.PackedUint64ExtensionLite, 123u);
TestPackedExtensionsLite msg = builder.Build();
ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
UnitTestLiteProtoFile.RegisterAllExtensions(registry);
TestPackedExtensionsLite.Builder copyBuilder = TestPackedExtensionsLite.CreateBuilder().MergeFrom(msg.ToByteArray(), registry);
TestPackedExtensionsLite copy = copyBuilder.Build();
Assert.AreEqual(msg.ToByteArray(), copy.ToByteArray());
Assert.AreEqual(true, copy.GetExtension(UnitTestLiteProtoFile.PackedBoolExtensionLite, 0));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.PackedDoubleExtensionLite, 0));
Assert.AreEqual(123u, copy.GetExtension(UnitTestLiteProtoFile.PackedFixed32ExtensionLite, 0));
Assert.AreEqual(123u, copy.GetExtension(UnitTestLiteProtoFile.PackedFixed64ExtensionLite, 0));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.PackedFloatExtensionLite, 0));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.PackedInt32ExtensionLite, 0));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.PackedInt64ExtensionLite, 0));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.PackedSfixed32ExtensionLite, 0));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.PackedSfixed64ExtensionLite, 0));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.PackedSint32ExtensionLite, 0));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.PackedSint64ExtensionLite, 0));
Assert.AreEqual(123u, copy.GetExtension(UnitTestLiteProtoFile.PackedUint32ExtensionLite, 0));
Assert.AreEqual(123u, copy.GetExtension(UnitTestLiteProtoFile.PackedUint64ExtensionLite, 0));
Assert.AreEqual(true, copy.GetExtension(UnitTestLiteProtoFile.PackedBoolExtensionLite, 1));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.PackedDoubleExtensionLite, 1));
Assert.AreEqual(123u, copy.GetExtension(UnitTestLiteProtoFile.PackedFixed32ExtensionLite, 1));
Assert.AreEqual(123u, copy.GetExtension(UnitTestLiteProtoFile.PackedFixed64ExtensionLite, 1));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.PackedFloatExtensionLite, 1));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.PackedInt32ExtensionLite, 1));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.PackedInt64ExtensionLite, 1));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.PackedSfixed32ExtensionLite, 1));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.PackedSfixed64ExtensionLite, 1));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.PackedSint32ExtensionLite, 1));
Assert.AreEqual(123, copy.GetExtension(UnitTestLiteProtoFile.PackedSint64ExtensionLite, 1));
Assert.AreEqual(123u, copy.GetExtension(UnitTestLiteProtoFile.PackedUint32ExtensionLite, 1));
Assert.AreEqual(123u, copy.GetExtension(UnitTestLiteProtoFile.PackedUint64ExtensionLite, 1));
}
}
}

@ -0,0 +1,162 @@
#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;
using Google.ProtocolBuffers.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers {
[TestFixture]
public class InteropLiteTest {
[Test]
public void TestConvertFromFullMinimal() {
TestInteropPerson person = TestInteropPerson.CreateBuilder()
.SetId(123)
.SetName("abc")
.Build();
Assert.IsTrue(person.IsInitialized);
TestInteropPersonLite copy = TestInteropPersonLite.ParseFrom(person.ToByteArray());
Assert.AreEqual(person.ToByteArray(), copy.ToByteArray());
}
[Test]
public void TestConvertFromFullComplete() {
TestInteropPerson person = TestInteropPerson.CreateBuilder()
.SetId(123)
.SetName("abc")
.SetEmail("abc@123.com")
.AddRangeCodes(new[] { 1, 2, 3 })
.AddPhone(TestInteropPerson.Types.PhoneNumber.CreateBuilder().SetNumber("555-1234").Build())
.AddPhone(TestInteropPerson.Types.PhoneNumber.CreateBuilder().SetNumber("555-5678").Build())
.AddAddresses(TestInteropPerson.Types.Addresses.CreateBuilder().SetAddress("123 Seseme").SetCity("Wonderland").SetState("NA").SetZip(12345).Build())
.SetExtension(UnitTestExtrasFullProtoFile.EmployeeId, TestInteropEmployeeId.CreateBuilder().SetNumber("123").Build())
.Build();
Assert.IsTrue(person.IsInitialized);
ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
UnitTestExtrasLiteProtoFile.RegisterAllExtensions(registry);
TestInteropPersonLite copy = TestInteropPersonLite.ParseFrom(person.ToByteArray(), registry);
Assert.AreEqual(person.ToByteArray(), copy.ToByteArray());
}
[Test]
public void TestConvertFromLiteMinimal() {
TestInteropPersonLite person = TestInteropPersonLite.CreateBuilder()
.SetId(123)
.SetName("abc")
.Build();
Assert.IsTrue(person.IsInitialized);
TestInteropPerson copy = TestInteropPerson.ParseFrom(person.ToByteArray());
Assert.AreEqual(person.ToByteArray(), copy.ToByteArray());
}
[Test]
public void TestConvertFromLiteComplete() {
TestInteropPersonLite person = TestInteropPersonLite.CreateBuilder()
.SetId(123)
.SetName("abc")
.SetEmail("abc@123.com")
.AddRangeCodes(new[] { 1, 2, 3 })
.AddPhone(TestInteropPersonLite.Types.PhoneNumber.CreateBuilder().SetNumber("555-1234").Build())
.AddPhone(TestInteropPersonLite.Types.PhoneNumber.CreateBuilder().SetNumber("555-5678").Build())
.AddAddresses(TestInteropPersonLite.Types.Addresses.CreateBuilder().SetAddress("123 Seseme").SetCity("Wonderland").SetState("NA").SetZip(12345).Build())
.SetExtension(UnitTestExtrasLiteProtoFile.EmployeeIdLite, TestInteropEmployeeIdLite.CreateBuilder().SetNumber("123").Build())
.Build();
Assert.IsTrue(person.IsInitialized);
ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
UnitTestExtrasFullProtoFile.RegisterAllExtensions(registry);
TestInteropPerson copy = TestInteropPerson.ParseFrom(person.ToByteArray(), registry);
Assert.AreEqual(person.ToByteArray(), copy.ToByteArray());
}
public ByteString AllBytes {
get {
byte[] bytes = new byte[256];
for (int i = 0; i < bytes.Length; i++)
bytes[i] = (byte)i;
return ByteString.CopyFrom(bytes);
}
}
[Test]
public void TestCompareStringValues() {
TestInteropPersonLite person = TestInteropPersonLite.CreateBuilder()
.SetId(123)
.SetName("abc")
.SetEmail("abc@123.com")
.AddRangeCodes(new[] { 1, 2, 3 })
.AddPhone(TestInteropPersonLite.Types.PhoneNumber.CreateBuilder().SetNumber("555-1234").Build())
.AddPhone(TestInteropPersonLite.Types.PhoneNumber.CreateBuilder().SetNumber(System.Text.Encoding.ASCII.GetString(AllBytes.ToByteArray())).Build())
.AddAddresses(TestInteropPersonLite.Types.Addresses.CreateBuilder().SetAddress("123 Seseme").SetCity("Wonderland").SetState("NA").SetZip(12345).Build())
.SetExtension(UnitTestExtrasLiteProtoFile.EmployeeIdLite, TestInteropEmployeeIdLite.CreateBuilder().SetNumber("123").Build())
.Build();
Assert.IsTrue(person.IsInitialized);
ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
UnitTestExtrasFullProtoFile.RegisterAllExtensions(registry);
TestInteropPerson copy = TestInteropPerson.ParseFrom(person.ToByteArray(), registry);
Assert.AreEqual(person.ToByteArray(), copy.ToByteArray());
TestInteropPerson.Builder copyBuilder = TestInteropPerson.CreateBuilder();
TextFormat.Merge(person.ToString().Replace("[protobuf_unittest_extra.employee_id_lite]", "[protobuf_unittest_extra.employee_id]"), registry, copyBuilder);
copy = copyBuilder.Build();
Assert.AreEqual(person.ToByteArray(), copy.ToByteArray());
string liteText = person.ToString().TrimEnd().Replace("\r", "");
string fullText = copy.ToString().TrimEnd().Replace("\r", "");
//map the extension type
liteText = liteText.Replace("[protobuf_unittest_extra.employee_id_lite]", "[protobuf_unittest_extra.employee_id]");
//lite version does not indent
while (fullText.IndexOf("\n ") >= 0)
fullText = fullText.Replace("\n ", "\n");
Assert.AreEqual(fullText, liteText);
}
}
}

@ -0,0 +1,112 @@
#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 {
/// <summary>
/// Miscellaneous tests for message operations that apply to both
/// generated and dynamic messages.
/// </summary>
[TestFixture]
public class LiteTest {
[Test]
public void TestLite() {
// Since lite messages are a subset of regular messages, we can mostly
// assume that the functionality of lite messages is already thoroughly
// tested by the regular tests. All this test really verifies is that
// a proto with optimize_for = LITE_RUNTIME compiles correctly when
// linked only against the lite library. That is all tested at compile
// time, leaving not much to do in this method. Let's just do some random
// stuff to make sure the lite message is actually here and usable.
TestAllTypesLite message =
TestAllTypesLite.CreateBuilder()
.SetOptionalInt32(123)
.AddRepeatedString("hello")
.SetOptionalNestedMessage(
TestAllTypesLite.Types.NestedMessage.CreateBuilder().SetBb(7))
.Build();
ByteString data = message.ToByteString();
TestAllTypesLite message2 = TestAllTypesLite.ParseFrom(data);
Assert.AreEqual(123, message2.OptionalInt32);
Assert.AreEqual(1, message2.RepeatedStringCount);
Assert.AreEqual("hello", message2.RepeatedStringList[0]);
Assert.AreEqual(7, message2.OptionalNestedMessage.Bb);
}
[Test]
public void TestLiteExtensions() {
// TODO(kenton): Unlike other features of the lite library, extensions are
// implemented completely differently from the regular library. We
// should probably test them more thoroughly.
TestAllExtensionsLite message =
TestAllExtensionsLite.CreateBuilder()
.SetExtension(UnitTestLiteProtoFile.OptionalInt32ExtensionLite, 123)
.AddExtension(UnitTestLiteProtoFile.RepeatedStringExtensionLite, "hello")
.SetExtension(UnitTestLiteProtoFile.OptionalNestedEnumExtensionLite,
TestAllTypesLite.Types.NestedEnum.BAZ)
.SetExtension(UnitTestLiteProtoFile.OptionalNestedMessageExtensionLite,
TestAllTypesLite.Types.NestedMessage.CreateBuilder().SetBb(7).Build())
.Build();
// Test copying a message, since coping extensions actually does use a
// different code path between lite and regular libraries, and as of this
// writing, parsing hasn't been implemented yet.
TestAllExtensionsLite message2 = message.ToBuilder().Build();
Assert.AreEqual(123, (int)message2.GetExtension(
UnitTestLiteProtoFile.OptionalInt32ExtensionLite));
Assert.AreEqual(1, message2.GetExtensionCount(
UnitTestLiteProtoFile.RepeatedStringExtensionLite));
Assert.AreEqual(1, message2.GetExtension(
UnitTestLiteProtoFile.RepeatedStringExtensionLite).Count);
Assert.AreEqual("hello", message2.GetExtension(
UnitTestLiteProtoFile.RepeatedStringExtensionLite, 0));
Assert.AreEqual(TestAllTypesLite.Types.NestedEnum.BAZ, message2.GetExtension(
UnitTestLiteProtoFile.OptionalNestedEnumExtensionLite));
Assert.AreEqual(7, message2.GetExtension(
UnitTestLiteProtoFile.OptionalNestedMessageExtensionLite).Bb);
}
}
}

@ -0,0 +1,219 @@
#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 System.Collections.Generic;
using Google.ProtocolBuffers.TestProtos;
namespace Google.ProtocolBuffers {
[TestFixture]
public class MissingFieldAndExtensionTest {
[Test]
public void TestRecoverMissingExtensions() {
const int optionalInt32 = 12345678;
TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder();
builder.SetExtension(UnitTestProtoFile.OptionalInt32Extension, optionalInt32);
builder.AddExtension(UnitTestProtoFile.RepeatedDoubleExtension, 1.1);
builder.AddExtension(UnitTestProtoFile.RepeatedDoubleExtension, 1.2);
builder.AddExtension(UnitTestProtoFile.RepeatedDoubleExtension, 1.3);
TestAllExtensions msg = builder.Build();
Assert.IsTrue(msg.HasExtension(UnitTestProtoFile.OptionalInt32Extension));
Assert.AreEqual(3, msg.GetExtensionCount(UnitTestProtoFile.RepeatedDoubleExtension));
byte[] bits = msg.ToByteArray();
TestAllExtensions copy = TestAllExtensions.ParseFrom(bits);
Assert.IsFalse(copy.HasExtension(UnitTestProtoFile.OptionalInt32Extension));
Assert.AreEqual(0, copy.GetExtensionCount(UnitTestProtoFile.RepeatedDoubleExtension));
Assert.AreNotEqual(msg, copy);
//Even though copy does not understand the typees they serialize correctly
byte[] copybits = copy.ToByteArray();
Assert.AreEqual(bits, copybits);
ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
UnitTestProtoFile.RegisterAllExtensions(registry);
//Now we can take those copy bits and restore the full message with extensions
copy = TestAllExtensions.ParseFrom(copybits, registry);
Assert.IsTrue(copy.HasExtension(UnitTestProtoFile.OptionalInt32Extension));
Assert.AreEqual(3, copy.GetExtensionCount(UnitTestProtoFile.RepeatedDoubleExtension));
Assert.AreEqual(msg, copy);
Assert.AreEqual(bits, copy.ToByteArray());
//If we modify the object this should all continue to work as before
copybits = copy.ToBuilder().Build().ToByteArray();
Assert.AreEqual(bits, copybits);
//If we replace extension the object this should all continue to work as before
copybits = copy.ToBuilder()
.SetExtension(UnitTestProtoFile.OptionalInt32Extension, optionalInt32)
.Build().ToByteArray();
Assert.AreEqual(bits, copybits);
}
[Test]
public void TestRecoverMissingFields() {
TestMissingFieldsA msga = TestMissingFieldsA.CreateBuilder()
.SetId(1001)
.SetName("Name")
.SetEmail("missing@field.value")
.Build();
//serialize to type B and verify all fields exist
TestMissingFieldsB msgb = TestMissingFieldsB.ParseFrom(msga.ToByteArray());
Assert.AreEqual(1001, msgb.Id);
Assert.AreEqual("Name", msgb.Name);
Assert.IsFalse(msgb.HasWebsite);
Assert.AreEqual(1, msgb.UnknownFields.FieldDictionary.Count);
Assert.AreEqual("missing@field.value", msgb.UnknownFields[TestMissingFieldsA.EmailFieldNumber].LengthDelimitedList[0].ToStringUtf8());
//serializes exactly the same (at least for this simple example)
Assert.AreEqual(msga.ToByteArray(), msgb.ToByteArray());
Assert.AreEqual(msga, TestMissingFieldsA.ParseFrom(msgb.ToByteArray()));
//now re-create an exact copy of A from serialized B
TestMissingFieldsA copya = TestMissingFieldsA.ParseFrom(msgb.ToByteArray());
Assert.AreEqual(msga, copya);
Assert.AreEqual(1001, copya.Id);
Assert.AreEqual("Name", copya.Name);
Assert.AreEqual("missing@field.value", copya.Email);
//Now we modify B... and try again
msgb = msgb.ToBuilder().SetWebsite("http://new.missing.field").Build();
//Does B still have the missing field?
Assert.AreEqual(1, msgb.UnknownFields.FieldDictionary.Count);
//Convert back to A and see if all fields are there?
copya = TestMissingFieldsA.ParseFrom(msgb.ToByteArray());
Assert.AreNotEqual(msga, copya);
Assert.AreEqual(1001, copya.Id);
Assert.AreEqual("Name", copya.Name);
Assert.AreEqual("missing@field.value", copya.Email);
Assert.AreEqual(1, copya.UnknownFields.FieldDictionary.Count);
Assert.AreEqual("http://new.missing.field", copya.UnknownFields[TestMissingFieldsB.WebsiteFieldNumber].LengthDelimitedList[0].ToStringUtf8());
//Lastly we can even still trip back to type B and see all fields:
TestMissingFieldsB copyb = TestMissingFieldsB.ParseFrom(copya.ToByteArray());
Assert.AreEqual(copya.ToByteArray().Length, copyb.ToByteArray().Length); //not exact order.
Assert.AreEqual(1001, copyb.Id);
Assert.AreEqual("Name", copyb.Name);
Assert.AreEqual("http://new.missing.field", copyb.Website);
Assert.AreEqual(1, copyb.UnknownFields.FieldDictionary.Count);
Assert.AreEqual("missing@field.value", copyb.UnknownFields[TestMissingFieldsA.EmailFieldNumber].LengthDelimitedList[0].ToStringUtf8());
}
[Test]
public void TestRecoverMissingMessage() {
TestMissingFieldsA.Types.SubA suba = TestMissingFieldsA.Types.SubA.CreateBuilder().SetCount(3).AddValues("a").AddValues("b").AddValues("c").Build();
TestMissingFieldsA msga = TestMissingFieldsA.CreateBuilder()
.SetId(1001)
.SetName("Name")
.SetTestA(suba)
.Build();
//serialize to type B and verify all fields exist
TestMissingFieldsB msgb = TestMissingFieldsB.ParseFrom(msga.ToByteArray());
Assert.AreEqual(1001, msgb.Id);
Assert.AreEqual("Name", msgb.Name);
Assert.AreEqual(1, msgb.UnknownFields.FieldDictionary.Count);
Assert.AreEqual(suba.ToString(), TestMissingFieldsA.Types.SubA.ParseFrom(msgb.UnknownFields[TestMissingFieldsA.TestAFieldNumber].LengthDelimitedList[0]).ToString());
//serializes exactly the same (at least for this simple example)
Assert.AreEqual(msga.ToByteArray(), msgb.ToByteArray());
Assert.AreEqual(msga, TestMissingFieldsA.ParseFrom(msgb.ToByteArray()));
//now re-create an exact copy of A from serialized B
TestMissingFieldsA copya = TestMissingFieldsA.ParseFrom(msgb.ToByteArray());
Assert.AreEqual(msga, copya);
Assert.AreEqual(1001, copya.Id);
Assert.AreEqual("Name", copya.Name);
Assert.AreEqual(suba, copya.TestA);
//Now we modify B... and try again
TestMissingFieldsB.Types.SubB subb = TestMissingFieldsB.Types.SubB.CreateBuilder().AddValues("test-b").Build();
msgb = msgb.ToBuilder().SetTestB(subb).Build();
//Does B still have the missing field?
Assert.AreEqual(1, msgb.UnknownFields.FieldDictionary.Count);
//Convert back to A and see if all fields are there?
copya = TestMissingFieldsA.ParseFrom(msgb.ToByteArray());
Assert.AreNotEqual(msga, copya);
Assert.AreEqual(1001, copya.Id);
Assert.AreEqual("Name", copya.Name);
Assert.AreEqual(suba, copya.TestA);
Assert.AreEqual(1, copya.UnknownFields.FieldDictionary.Count);
Assert.AreEqual(subb.ToByteArray(), copya.UnknownFields[TestMissingFieldsB.TestBFieldNumber].LengthDelimitedList[0].ToByteArray());
//Lastly we can even still trip back to type B and see all fields:
TestMissingFieldsB copyb = TestMissingFieldsB.ParseFrom(copya.ToByteArray());
Assert.AreEqual(copya.ToByteArray().Length, copyb.ToByteArray().Length); //not exact order.
Assert.AreEqual(1001, copyb.Id);
Assert.AreEqual("Name", copyb.Name);
Assert.AreEqual(subb, copyb.TestB);
Assert.AreEqual(1, copyb.UnknownFields.FieldDictionary.Count);
}
[Test]
public void TestRestoreFromOtherType() {
TestInteropPerson person = TestInteropPerson.CreateBuilder()
.SetId(123)
.SetName("abc")
.SetEmail("abc@123.com")
.AddRangeCodes(new[] {1, 2, 3})
.AddPhone(TestInteropPerson.Types.PhoneNumber.CreateBuilder().SetNumber("555-1234").Build())
.AddPhone(TestInteropPerson.Types.PhoneNumber.CreateBuilder().SetNumber("555-5678").Build())
.AddAddresses(TestInteropPerson.Types.Addresses.CreateBuilder().SetAddress("123 Seseme").SetCity("Wonderland").SetState("NA").SetZip(12345).Build())
.SetExtension(UnitTestExtrasFullProtoFile.EmployeeId, TestInteropEmployeeId.CreateBuilder().SetNumber("123").Build())
.Build();
Assert.IsTrue(person.IsInitialized);
TestEmptyMessage temp = TestEmptyMessage.ParseFrom(person.ToByteArray());
Assert.AreEqual(7, temp.UnknownFields.FieldDictionary.Count);
temp = temp.ToBuilder().Build();
Assert.AreEqual(7, temp.UnknownFields.FieldDictionary.Count);
ExtensionRegistry registry = ExtensionRegistry.CreateInstance();
UnitTestExtrasFullProtoFile.RegisterAllExtensions(registry);
TestInteropPerson copy = TestInteropPerson.ParseFrom(temp.ToByteArray(), registry);
Assert.AreEqual(person, copy);
Assert.AreEqual(person.ToByteArray(), copy.ToByteArray());
}
}
}

@ -0,0 +1,110 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{EE01ED24-3750-4567-9A23-1DB676A15610}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Google.ProtocolBuffers</RootNamespace>
<AssemblyName>Google.ProtocolBuffersLite.Test</AssemblyName>
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>..\ProtocolBuffers.Test\Properties\Google.ProtocolBuffers.Test.snk</AssemblyOriginatorKeyFile>
<FileUpgradeFlags>
</FileUpgradeFlags>
<OldToolsVersion>3.5</OldToolsVersion>
<UpgradeBackupLocation />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoStdLib>true</NoStdLib>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoStdLib>true</NoStdLib>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug_Silverlight2|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug_Silverlight2\</OutputPath>
<DefineConstants>DEBUG;TRACE;SILVERLIGHT2</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoStdLib>true</NoStdLib>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release_Silverlight2|AnyCPU'">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release_Silverlight2\</OutputPath>
<DefineConstants>TRACE;SILVERLIGHT2</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoStdLib>true</NoStdLib>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="nunit.framework, Version=2.2.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\NUnit 2.2.8.0\nunit.framework.dll</HintPath>
</Reference>
<Reference Include="Rhino.Mocks, Version=3.5.0.2, Culture=neutral, PublicKeyToken=0b3305902db7183f, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\Rhino.Mocks.dll</HintPath>
</Reference>
<Reference Include="mscorlib" />
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\ProtocolBuffers.Test\Properties\AssemblyInfo.cs">
<Link>Properties\AssemblyInfo.cs</Link>
</Compile>
<Compile Include="AbstractBuilderLiteTest.cs" />
<Compile Include="AbstractMessageLiteTest.cs" />
<Compile Include="ExtendableBuilderLiteTest.cs" />
<Compile Include="ExtendableMessageLiteTest.cs" />
<Compile Include="LiteTest.cs" />
<Compile Include="TestLiteByApi.cs" />
<Compile Include="TestProtos\UnitTestExtrasLiteProtoFile.cs" />
<Compile Include="TestProtos\UnitTestImportLiteProtoFile.cs" />
<Compile Include="TestProtos\UnitTestLiteProtoFile.cs" />
</ItemGroup>
<ItemGroup>
<None Include="..\ProtocolBuffers.Test\Properties\Google.ProtocolBuffers.Test.snk">
<Link>Properties\Google.ProtocolBuffers.Test.snk</Link>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ProtocolBuffers\ProtocolBuffersLite.csproj">
<Project>{6969BDCE-D925-43F3-94AC-A531E6DF2591}</Project>
<Name>ProtocolBuffersLite</Name>
<Private>True</Private>
</ProjectReference>
</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.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

@ -0,0 +1,115 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{EEFFED24-3750-4567-9A23-1DB676A15610}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Google.ProtocolBuffers</RootNamespace>
<AssemblyName>Google.ProtocolBuffersMixedLite.Test</AssemblyName>
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>..\ProtocolBuffers.Test\Properties\Google.ProtocolBuffers.Test.snk</AssemblyOriginatorKeyFile>
<FileUpgradeFlags>
</FileUpgradeFlags>
<OldToolsVersion>3.5</OldToolsVersion>
<UpgradeBackupLocation />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<NoStdLib>true</NoStdLib>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<NoStdLib>true</NoStdLib>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug_Silverlight2|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug_Silverlight2\</OutputPath>
<DefineConstants>DEBUG;TRACE;SILVERLIGHT2</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoStdLib>true</NoStdLib>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release_Silverlight2|AnyCPU'">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release_Silverlight2\</OutputPath>
<DefineConstants>TRACE;SILVERLIGHT2</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<NoStdLib>true</NoStdLib>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="nunit.framework, Version=2.2.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\NUnit 2.2.8.0\nunit.framework.dll</HintPath>
</Reference>
<Reference Include="Rhino.Mocks, Version=3.5.0.2, Culture=neutral, PublicKeyToken=0b3305902db7183f, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\Rhino.Mocks.dll</HintPath>
</Reference>
<Reference Include="mscorlib" />
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\ProtocolBuffers.Test\Properties\AssemblyInfo.cs">
<Link>Properties\AssemblyInfo.cs</Link>
</Compile>
<Compile Include="AbstractBuilderLiteTest.cs" />
<Compile Include="AbstractMessageLiteTest.cs" />
<Compile Include="ExtendableBuilderLiteTest.cs" />
<Compile Include="ExtendableMessageLiteTest.cs" />
<Compile Include="InteropLiteTest.cs" />
<Compile Include="LiteTest.cs" />
<Compile Include="MissingFieldAndExtensionTest.cs" />
<Compile Include="TestLiteByApi.cs" />
<Compile Include="TestProtos\UnitTestExtrasFullProtoFile.cs" />
<Compile Include="TestProtos\UnitTestExtrasLiteProtoFile.cs" />
<Compile Include="TestProtos\UnitTestImportLiteProtoFile.cs" />
<Compile Include="TestProtos\UnitTestImportProtoFile.cs" />
<Compile Include="TestProtos\UnitTestLiteImportNonLiteProtoFile.cs" />
<Compile Include="TestProtos\UnitTestLiteProtoFile.cs" />
<Compile Include="TestProtos\UnitTestProtoFile.cs" />
</ItemGroup>
<ItemGroup>
<None Include="..\ProtocolBuffers.Test\Properties\Google.ProtocolBuffers.Test.snk">
<Link>Properties\Google.ProtocolBuffers.Test.snk</Link>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ProtocolBuffers\ProtocolBuffers.csproj">
<Project>{6908BDCE-D925-43F3-94AC-A531E6DF2591}</Project>
<Name>ProtocolBuffers</Name>
</ProjectReference>
</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.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

@ -0,0 +1,116 @@
#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;
using Google.ProtocolBuffers.TestProtos;
using NUnit.Framework;
namespace Google.ProtocolBuffers {
[TestFixture]
public class TestLiteByApi {
[Test]
public void TestAllTypesEquality() {
TestAllTypesLite msg = TestAllTypesLite.DefaultInstance;
TestAllTypesLite copy = msg.ToBuilder().Build();
Assert.AreEqual(msg.GetHashCode(), copy.GetHashCode());
Assert.IsTrue(msg.Equals(copy));
msg = msg.ToBuilder().SetOptionalString("Hi").Build();
Assert.AreNotEqual(msg.GetHashCode(), copy.GetHashCode());
Assert.IsFalse(msg.Equals(copy));
copy = copy.ToBuilder().SetOptionalString("Hi").Build();
Assert.AreEqual(msg.GetHashCode(), copy.GetHashCode());
Assert.IsTrue(msg.Equals(copy));
}
[Test]
public void TestEqualityOnExtensions() {
TestAllExtensionsLite msg = TestAllExtensionsLite.DefaultInstance;
TestAllExtensionsLite copy = msg.ToBuilder().Build();
Assert.AreEqual(msg.GetHashCode(), copy.GetHashCode());
Assert.IsTrue(msg.Equals(copy));
msg = msg.ToBuilder().SetExtension(UnitTestLiteProtoFile.OptionalStringExtensionLite, "Hi").Build();
Assert.AreNotEqual(msg.GetHashCode(), copy.GetHashCode());
Assert.IsFalse(msg.Equals(copy));
copy = copy.ToBuilder().SetExtension(UnitTestLiteProtoFile.OptionalStringExtensionLite, "Hi").Build();
Assert.AreEqual(msg.GetHashCode(), copy.GetHashCode());
Assert.IsTrue(msg.Equals(copy));
}
[Test]
public void TestAllTypesToString() {
TestAllTypesLite msg = TestAllTypesLite.DefaultInstance;
TestAllTypesLite copy = msg.ToBuilder().Build();
Assert.AreEqual(msg.ToString(), copy.ToString());
Assert.IsEmpty(msg.ToString());
msg = msg.ToBuilder().SetOptionalInt32(-1).Build();
Assert.AreEqual("optional_int32: -1", msg.ToString().TrimEnd());
msg = msg.ToBuilder().SetOptionalString("abc123").Build();
Assert.AreEqual("optional_int32: -1\noptional_string: \"abc123\"", msg.ToString().Replace("\r", "").TrimEnd());
}
[Test]
public void TestAllTypesDefaultedRoundTrip() {
TestAllTypesLite msg = TestAllTypesLite.DefaultInstance;
Assert.IsTrue(msg.IsInitialized);
TestAllTypesLite copy = TestAllTypesLite.CreateBuilder().MergeFrom(msg.ToByteArray()).Build();
Assert.AreEqual(msg.ToByteArray(), copy.ToByteArray());
}
[Test]
public void TestAllTypesModifiedRoundTrip() {
TestAllTypesLite msg = TestAllTypesLite.DefaultInstance;
msg.ToBuilder()
.SetOptionalBool(true)
.SetOptionalCord("Hi")
.SetOptionalDouble(1.123)
.SetOptionalForeignEnum(ForeignEnumLite.FOREIGN_LITE_FOO)
.SetOptionalForeignMessage(ForeignMessageLite.CreateBuilder().SetC('c').Build())
.SetOptionalGroup(TestAllTypesLite.Types.OptionalGroup.CreateBuilder().SetA('a').Build())
.SetOptionalImportEnum(ImportEnumLite.IMPORT_LITE_BAR)
.SetOptionalInt32(32)
.SetOptionalInt64(64)
.SetOptionalNestedEnum(TestAllTypesLite.Types.NestedEnum.FOO)
.SetOptionalString("SetOptionalString")
.AddRepeatedGroup(TestAllTypesLite.Types.RepeatedGroup.CreateBuilder().SetA('a').Build())
.AddRepeatedGroup(TestAllTypesLite.Types.RepeatedGroup.CreateBuilder().SetA('A').Build())
;
TestAllTypesLite copy = TestAllTypesLite.CreateBuilder().MergeFrom(msg.ToByteArray()).Build();
Assert.AreEqual(msg.ToByteArray(), copy.ToByteArray());
}
}
}

@ -0,0 +1,246 @@
// Generated by ProtoGen, Version=0.9.0.0, Culture=neutral, PublicKeyToken=8fd7408b07f8d2cd. DO NOT EDIT!
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 {
public static partial class UnitTestImportLiteProtoFile {
#region Extension registration
public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {
}
#endregion
#region Static variables
#endregion
#region Extensions
internal static readonly object Descriptor;
static UnitTestImportLiteProtoFile() {
Descriptor = null;
}
#endregion
}
#region Enums
public enum ImportEnumLite {
IMPORT_LITE_FOO = 7,
IMPORT_LITE_BAR = 8,
IMPORT_LITE_BAZ = 9,
}
#endregion
#region Messages
public sealed partial class ImportMessageLite : pb::GeneratedMessageLite<ImportMessageLite, ImportMessageLite.Builder> {
private static readonly ImportMessageLite defaultInstance = new Builder().BuildPartial();
public static ImportMessageLite DefaultInstance {
get { return defaultInstance; }
}
public override ImportMessageLite DefaultInstanceForType {
get { return defaultInstance; }
}
protected override ImportMessageLite ThisMessage {
get { return this; }
}
public const int DFieldNumber = 1;
private bool hasD;
private int d_ = 0;
public bool HasD {
get { return hasD; }
}
public int D {
get { return d_; }
}
public override bool IsInitialized {
get {
return true;
}
}
public override void WriteTo(pb::CodedOutputStream output) {
int size = SerializedSize;
if (HasD) {
output.WriteInt32(1, D);
}
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (HasD) {
size += pb::CodedOutputStream.ComputeInt32Size(1, D);
}
memoizedSerializedSize = size;
return size;
}
}
#region Lite runtime methods
public override int GetHashCode() {
int hash = GetType().GetHashCode();
if (hasD) hash ^= d_.GetHashCode();
return hash;
}
public override bool Equals(object obj) {
ImportMessageLite other = obj as ImportMessageLite;
if (other == null) return false;
if (hasD != other.hasD || (hasD && !d_.Equals(other.d_))) return false;
return true;
}
public override void PrintTo(global::System.IO.TextWriter writer) {
PrintField("d", hasD, d_, writer);
}
#endregion
public static ImportMessageLite ParseFrom(pb::ByteString data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static ImportMessageLite ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static ImportMessageLite ParseFrom(byte[] data) {
return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();
}
public static ImportMessageLite ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();
}
public static ImportMessageLite ParseFrom(global::System.IO.Stream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static ImportMessageLite ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
public static ImportMessageLite ParseDelimitedFrom(global::System.IO.Stream input) {
return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();
}
public static ImportMessageLite ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {
return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();
}
public static ImportMessageLite ParseFrom(pb::CodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static ImportMessageLite ParseFrom(pb::CodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
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(ImportMessageLite prototype) {
return (Builder) new Builder().MergeFrom(prototype);
}
public sealed partial class Builder : pb::GeneratedBuilderLite<ImportMessageLite, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {}
ImportMessageLite result = new ImportMessageLite();
protected override ImportMessageLite MessageBeingBuilt {
get { return result; }
}
public override Builder Clear() {
result = new ImportMessageLite();
return this;
}
public override Builder Clone() {
return new Builder().MergeFrom(result);
}
public override ImportMessageLite DefaultInstanceForType {
get { return global::Google.ProtocolBuffers.TestProtos.ImportMessageLite.DefaultInstance; }
}
public override ImportMessageLite BuildPartial() {
if (result == null) {
throw new global::System.InvalidOperationException("build() has already been called on this Builder");
}
ImportMessageLite returnMe = result;
result = null;
return returnMe;
}
public override Builder MergeFrom(pb::IMessageLite other) {
if (other is ImportMessageLite) {
return MergeFrom((ImportMessageLite) other);
} else {
base.MergeFrom(other);
return this;
}
}
public override Builder MergeFrom(ImportMessageLite other) {
if (other == global::Google.ProtocolBuffers.TestProtos.ImportMessageLite.DefaultInstance) return this;
if (other.HasD) {
D = other.D;
}
return this;
}
public override Builder MergeFrom(pb::CodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::CodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
while (true) {
uint tag = input.ReadTag();
switch (tag) {
case 0: {
return this;
}
default: {
if (pb::WireFormat.IsEndGroupTag(tag)) {
return this;
}
ParseUnknownField(input, extensionRegistry, tag);
break;
}
case 8: {
D = input.ReadInt32();
break;
}
}
}
}
public bool HasD {
get { return result.HasD; }
}
public int D {
get { return result.D; }
set { SetD(value); }
}
public Builder SetD(int value) {
result.hasD = true;
result.d_ = value;
return this;
}
public Builder ClearD() {
result.hasD = false;
result.d_ = 0;
return this;
}
}
static ImportMessageLite() {
object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.UnitTestImportLiteProtoFile.Descriptor, null);
}
}
#endregion
}

@ -0,0 +1,280 @@
// Generated by ProtoGen, Version=0.9.0.0, Culture=neutral, PublicKeyToken=8fd7408b07f8d2cd. DO NOT EDIT!
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 {
public static partial class UnitTestImportProtoFile {
#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 UnitTestImportProtoFile() {
byte[] descriptorData = global::System.Convert.FromBase64String(
"CiVnb29nbGUvcHJvdG9idWYvdW5pdHRlc3RfaW1wb3J0LnByb3RvEhhwcm90" +
"b2J1Zl91bml0dGVzdF9pbXBvcnQaJGdvb2dsZS9wcm90b2J1Zi9jc2hhcnBf" +
"b3B0aW9ucy5wcm90byIaCg1JbXBvcnRNZXNzYWdlEgkKAWQYASABKAUqPAoK" +
"SW1wb3J0RW51bRIOCgpJTVBPUlRfRk9PEAcSDgoKSU1QT1JUX0JBUhAIEg4K" +
"CklNUE9SVF9CQVoQCUJbChhjb20uZ29vZ2xlLnByb3RvYnVmLnRlc3RIAcI+" +
"PAohR29vZ2xlLlByb3RvY29sQnVmZmVycy5UZXN0UHJvdG9zEhdVbml0VGVz" +
"dEltcG9ydFByb3RvRmlsZQ==");
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.DescriptorProtos.CSharpOptions.RegisterAllExtensions(registry);
return registry;
};
pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData,
new pbd::FileDescriptor[] {
global::Google.ProtocolBuffers.DescriptorProtos.CSharpOptions.Descriptor,
}, assigner);
}
#endregion
}
#region Enums
public enum ImportEnum {
IMPORT_FOO = 7,
IMPORT_BAR = 8,
IMPORT_BAZ = 9,
}
#endregion
#region Messages
public sealed partial class ImportMessage : pb::GeneratedMessage<ImportMessage, ImportMessage.Builder> {
private static readonly ImportMessage defaultInstance = new Builder().BuildPartial();
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.UnitTestImportProtoFile.internal__static_protobuf_unittest_import_ImportMessage__Descriptor; }
}
protected override pb::FieldAccess.FieldAccessorTable<ImportMessage, ImportMessage.Builder> InternalFieldAccessors {
get { return global::Google.ProtocolBuffers.TestProtos.UnitTestImportProtoFile.internal__static_protobuf_unittest_import_ImportMessage__FieldAccessorTable; }
}
public const int DFieldNumber = 1;
private bool hasD;
private int d_ = 0;
public bool HasD {
get { return hasD; }
}
public int D {
get { return d_; }
}
public override bool IsInitialized {
get {
return true;
}
}
public override void WriteTo(pb::CodedOutputStream output) {
int size = SerializedSize;
if (HasD) {
output.WriteInt32(1, D);
}
UnknownFields.WriteTo(output);
}
private int memoizedSerializedSize = -1;
public override int SerializedSize {
get {
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::CodedInputStream input) {
return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();
}
public static ImportMessage ParseFrom(pb::CodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();
}
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 (Builder) new Builder().MergeFrom(prototype);
}
public sealed partial class Builder : pb::GeneratedBuilder<ImportMessage, Builder> {
protected override Builder ThisBuilder {
get { return this; }
}
public Builder() {}
ImportMessage result = new ImportMessage();
protected override ImportMessage MessageBeingBuilt {
get { return result; }
}
public override Builder Clear() {
result = new ImportMessage();
return this;
}
public override Builder Clone() {
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 (result == null) {
throw new global::System.InvalidOperationException("build() has already been called on this Builder");
}
ImportMessage returnMe = result;
result = null;
return returnMe;
}
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;
if (other.HasD) {
D = other.D;
}
this.MergeUnknownFields(other.UnknownFields);
return this;
}
public override Builder MergeFrom(pb::CodedInputStream input) {
return MergeFrom(input, pb::ExtensionRegistry.Empty);
}
public override Builder MergeFrom(pb::CodedInputStream input, pb::ExtensionRegistry extensionRegistry) {
pb::UnknownFieldSet.Builder unknownFields = null;
while (true) {
uint tag = input.ReadTag();
switch (tag) {
case 0: {
if (unknownFields != null) {
this.UnknownFields = unknownFields.Build();
}
return this;
}
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);
break;
}
case 8: {
D = input.ReadInt32();
break;
}
}
}
}
public bool HasD {
get { return result.HasD; }
}
public int D {
get { return result.D; }
set { SetD(value); }
}
public Builder SetD(int value) {
result.hasD = true;
result.d_ = value;
return this;
}
public Builder ClearD() {
result.hasD = false;
result.d_ = 0;
return this;
}
}
static ImportMessage() {
object.ReferenceEquals(global::Google.ProtocolBuffers.TestProtos.UnitTestImportProtoFile.Descriptor, null);
}
}
#endregion
}

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

Loading…
Cancel
Save