Commit 1738462b authored by Jon Skeet's avatar Jon Skeet

First commit of lite code - more to come

parents 0c58d060 00ca6080
...@@ -8,6 +8,8 @@ src/ProtocolBuffers/obj/ ...@@ -8,6 +8,8 @@ src/ProtocolBuffers/obj/
src/ProtocolBuffers/objCF src/ProtocolBuffers/objCF
src/ProtocolBuffers.Test/bin/ src/ProtocolBuffers.Test/bin/
src/ProtocolBuffers.Test/obj/ src/ProtocolBuffers.Test/obj/
src/ProtocolBuffersLite.Test/bin/
src/ProtocolBuffersLite.Test/obj/
src/ProtoBench/bin/ src/ProtoBench/bin/
src/ProtoBench/obj/ src/ProtoBench/obj/
src/ProtoDump/bin/ src/ProtoDump/bin/
...@@ -34,4 +36,4 @@ _ReSharper.* ...@@ -34,4 +36,4 @@ _ReSharper.*
mono/TestResult.xml mono/TestResult.xml
mono/.libs mono/.libs
mono/*.exe mono/*.exe
mono/*.dll mono/*.dll
\ No newline at end of file
No preview for this file type
// 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;
}
// 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 { ...@@ -247,13 +247,31 @@ message FileOptions {
// Generated classes can be optimized for speed or code size. // Generated classes can be optimized for speed or code size.
enum OptimizeMode { enum OptimizeMode {
SPEED = 1; // Generate complete code for parsing, serialization, etc. SPEED = 1; // Generate complete code for parsing, serialization,
CODE_SIZE = 2; // Use ReflectionOps to implement these methods. // 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]; 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. // The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999; repeated UninterpretedOption uninterpreted_option = 999;
...@@ -282,6 +300,11 @@ message MessageOptions { ...@@ -282,6 +300,11 @@ message MessageOptions {
// the protocol compiler. // the protocol compiler.
optional bool message_set_wire_format = 1 [default=false]; 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. // The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999; repeated UninterpretedOption uninterpreted_option = 999;
...@@ -294,8 +317,11 @@ message FieldOptions { ...@@ -294,8 +317,11 @@ message FieldOptions {
// representation of the field than it normally would. See the specific // representation of the field than it normally would. See the specific
// options below. This option is not yet implemented in the open source // options below. This option is not yet implemented in the open source
// release -- sorry, we'll try to include it in a future version! // release -- sorry, we'll try to include it in a future version!
optional CType ctype = 1; optional CType ctype = 1 [default = STRING];
enum CType { enum CType {
// Default mode.
STRING = 0;
CORD = 1; CORD = 1;
STRING_PIECE = 2; STRING_PIECE = 2;
...@@ -306,12 +332,13 @@ message FieldOptions { ...@@ -306,12 +332,13 @@ message FieldOptions {
// a single length-delimited blob. // a single length-delimited blob.
optional bool packed = 2; optional bool packed = 2;
// Is this field deprecated? // Is this field deprecated?
// Depending on the target platform, this can emit Deprecated annotations // Depending on the target platform, this can emit Deprecated annotations
// for accessors, or it will be completely ignored; in the very least, this // for accessors, or it will be completely ignored; in the very least, this
// is a formalization for deprecating fields. // is a formalization for deprecating fields.
optional bool deprecated = 3 [default=false]; optional bool deprecated = 3 [default=false];
// EXPERIMENTAL. DO NOT USE. // EXPERIMENTAL. DO NOT USE.
// For "map" fields, the name of the field in the enclosed type that // For "map" fields, the name of the field in the enclosed type that
// is the key for this map. For example, suppose we have: // is the key for this map. For example, suppose we have:
...@@ -334,6 +361,7 @@ message FieldOptions { ...@@ -334,6 +361,7 @@ message FieldOptions {
} }
message EnumOptions { message EnumOptions {
// The parser stores options it doesn't recognize here. See above. // The parser stores options it doesn't recognize here. See above.
repeated UninterpretedOption uninterpreted_option = 999; repeated UninterpretedOption uninterpreted_option = 999;
......
...@@ -161,6 +161,10 @@ message TestAllTypes { ...@@ -161,6 +161,10 @@ message TestAllTypes {
optional string default_cord = 85 [ctype=CORD,default="123"]; 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 // Define these after TestAllTypes to make sure the compiler can handle
// that. // that.
message ForeignMessage { message ForeignMessage {
...@@ -275,6 +279,14 @@ extend TestAllExtensions { ...@@ -275,6 +279,14 @@ extend TestAllExtensions {
optional string default_cord_extension = 85 [ctype=CORD, default="123"]; 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 // We have separate messages for testing required fields because it's
// annoying to have to fill in required fields in TestProto in order to // 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 // do anything with it. Note that we don't need to test every type of
...@@ -346,6 +358,12 @@ message TestEmptyMessageWithExtensions { ...@@ -346,6 +358,12 @@ message TestEmptyMessageWithExtensions {
extensions 1 to max; 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. // Test that really large tag numbers don't break anything.
message TestReallyLargeTagNumber { message TestReallyLargeTagNumber {
// The largest possible tag number is 2^28 - 1, since the wire format uses // The largest possible tag number is 2^28 - 1, since the wire format uses
...@@ -370,13 +388,14 @@ message TestMutualRecursionB { ...@@ -370,13 +388,14 @@ message TestMutualRecursionB {
} }
// Test that groups have disjoint field numbers from their siblings and // Test that groups have disjoint field numbers from their siblings and
// parents. This is NOT possible in proto1; only proto2. When outputting // parents. This is NOT possible in proto1; only proto2. When attempting
// proto1, the dup fields should be dropped. // to compile with proto1, this will emit an error; so we only include it
message TestDupFieldNumber { // in protobuf_unittest_proto.
optional int32 a = 1; message TestDupFieldNumber { // NO_PROTO1
optional group Foo = 2 { optional int32 a = 1; } optional int32 a = 1; // NO_PROTO1
optional group Bar = 3 { optional int32 a = 1; } 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. // Needed for a Python test.
...@@ -456,8 +475,37 @@ message TestExtremeDefaultValues { ...@@ -456,8 +475,37 @@ message TestExtremeDefaultValues {
// the UTF-8 text directly into this text file rather than escape it, but // 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.) // lots of people use editors that would be confused by this.)
optional string utf8_string = 6 [default = "\341\210\264"]; 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 { message TestPackedTypes {
repeated int32 packed_int32 = 90 [packed = true]; repeated int32 packed_int32 = 90 [packed = true];
repeated int64 packed_int64 = 91 [packed = true]; repeated int64 packed_int64 = 91 [packed = true];
...@@ -475,6 +523,25 @@ message TestPackedTypes { ...@@ -475,6 +523,25 @@ message TestPackedTypes {
repeated ForeignEnum packed_enum = 103 [packed = true]; 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 { message TestPackedExtensions {
extensions 1 to max; extensions 1 to max;
} }
...@@ -496,6 +563,47 @@ extend TestPackedExtensions { ...@@ -496,6 +563,47 @@ extend TestPackedExtensions {
repeated ForeignEnum packed_enum_extension = 103 [packed = true]; 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. // Test that RPC services work.
message FooRequest {} message FooRequest {}
message FooResponse {} message FooResponse {}
......
...@@ -72,7 +72,9 @@ extend google.protobuf.EnumOptions { ...@@ -72,7 +72,9 @@ extend google.protobuf.EnumOptions {
optional sfixed32 enum_opt1 = 7753576; 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 { extend google.protobuf.ServiceOptions {
optional sint64 service_opt1 = 7887650; optional sint64 service_opt1 = 7887650;
...@@ -101,7 +103,7 @@ message TestMessageWithCustomOptions { ...@@ -101,7 +103,7 @@ message TestMessageWithCustomOptions {
option (enum_opt1) = -789; option (enum_opt1) = -789;
ANENUM_VAL1 = 1; ANENUM_VAL1 = 1;
ANENUM_VAL2 = 2; ANENUM_VAL2 = 2 [(enum_value_opt1) = 123];
} }
} }
...@@ -208,6 +210,8 @@ message SettingRealsFromNegativeInts { ...@@ -208,6 +210,8 @@ message SettingRealsFromNegativeInts {
message ComplexOptionType1 { message ComplexOptionType1 {
optional int32 foo = 1; optional int32 foo = 1;
optional int32 foo2 = 2;
optional int32 foo3 = 3;
extensions 100 to max; extensions 100 to max;
} }
......
// 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.)
This source diff could not be displayed because it is too large. You can view the blob instead.
// 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;
}
This diff is collapsed.
// 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;
}
// 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);
}
// 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 pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections; using pbc = global::Google.ProtocolBuffers.Collections;
......
...@@ -78,7 +78,7 @@ ...@@ -78,7 +78,7 @@
<ItemGroup> <ItemGroup>
<Reference Include="nunit.framework, Version=2.2.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77"> <Reference Include="nunit.framework, Version=2.2.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77">
<SpecificVersion>False</SpecificVersion> <SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\nunit.framework.dll</HintPath> <HintPath>..\..\lib\NUnit 2.2.8.0\nunit.framework.dll</HintPath>
</Reference> </Reference>
<Reference Include="Rhino.Mocks, Version=3.5.0.2, Culture=neutral, PublicKeyToken=0b3305902db7183f, processorArchitecture=MSIL"> <Reference Include="Rhino.Mocks, Version=3.5.0.2, Culture=neutral, PublicKeyToken=0b3305902db7183f, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion> <SpecificVersion>False</SpecificVersion>
......
...@@ -88,10 +88,12 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -88,10 +88,12 @@ namespace Google.ProtocolBuffers.ProtoGen {
// TODO(jonskeet): Make a more efficient way of doing this // TODO(jonskeet): Make a more efficient way of doing this
writer.WriteLine("int rawValue = input.ReadEnum();"); writer.WriteLine("int rawValue = input.ReadEnum();");
writer.WriteLine("if (!global::System.Enum.IsDefined(typeof({0}), rawValue)) {{", TypeName); writer.WriteLine("if (!global::System.Enum.IsDefined(typeof({0}), rawValue)) {{", TypeName);
writer.WriteLine(" if (unknownFields == null) {"); // First unknown field - create builder now if (!UseLiteRuntime) {
writer.WriteLine(" unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);"); writer.WriteLine(" if (unknownFields == null) {"); // First unknown field - create builder now
writer.WriteLine(" }"); writer.WriteLine(" unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);");
writer.WriteLine(" unknownFields.MergeVarintField({0}, (ulong) rawValue);", Number); writer.WriteLine(" }");
writer.WriteLine(" unknownFields.MergeVarintField({0}, (ulong) rawValue);", Number);
}
writer.WriteLine("} else {"); writer.WriteLine("} else {");
writer.WriteLine(" {0} = ({1}) rawValue;", PropertyName, TypeName); writer.WriteLine(" {0} = ({1}) rawValue;", PropertyName, TypeName);
writer.WriteLine("}"); writer.WriteLine("}");
...@@ -106,7 +108,19 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -106,7 +108,19 @@ namespace Google.ProtocolBuffers.ProtoGen {
public void GenerateSerializedSizeCode(TextGenerator writer) { public void GenerateSerializedSizeCode(TextGenerator writer) {
writer.WriteLine("if (Has{0}) {{", PropertyName); writer.WriteLine("if (Has{0}) {{", PropertyName);
writer.WriteLine(" size += pb::CodedOutputStream.ComputeEnumSize({0}, (int) {1});", Number, 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 @@ ...@@ -32,16 +32,20 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion #endregion
using System;
using System.Globalization;
using Google.ProtocolBuffers.Descriptors; using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers.ProtoGen { 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 scope;
private readonly string type; private readonly string type;
private readonly string name; private readonly string name;
internal ExtensionGenerator(FieldDescriptor descriptor) : base(descriptor) { internal ExtensionGenerator(FieldDescriptor descriptor)
: base(descriptor) {
if (Descriptor.ExtensionScope != null) { if (Descriptor.ExtensionScope != null) {
scope = GetClassName(Descriptor.ExtensionScope); scope = GetClassName(Descriptor.ExtensionScope);
} else { } else {
...@@ -58,14 +62,24 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -58,14 +62,24 @@ namespace Google.ProtocolBuffers.ProtoGen {
type = DescriptorUtil.GetMappedTypeName(Descriptor.MappedType); type = DescriptorUtil.GetMappedTypeName(Descriptor.MappedType);
break; break;
} }
extends = GetClassName(Descriptor.ContainingType);
name = Descriptor.CSharpOptions.PropertyName; name = Descriptor.CSharpOptions.PropertyName;
} }
public void Generate(TextGenerator writer) { public void Generate(TextGenerator writer) {
writer.WriteLine ("public const int {0} = {1};", GetFieldConstantName(Descriptor), Descriptor.FieldNumber); writer.WriteLine("public const int {0} = {1};", GetFieldConstantName(Descriptor), Descriptor.FieldNumber);
if (Descriptor.IsRepeated) {
if (!Descriptor.IsCLSCompliant && Descriptor.File.CSharpOptions.ClsCompliance) 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("[global::System.CLSCompliant(false)]");
} }
writer.WriteLine("{0} static pb::GeneratedExtensionBase<scg::IList<{1}>> {2};", ClassAccessLevel, type, name); writer.WriteLine("{0} static pb::GeneratedExtensionBase<scg::IList<{1}>> {2};", ClassAccessLevel, type, name);
...@@ -78,7 +92,27 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -78,7 +92,27 @@ namespace Google.ProtocolBuffers.ProtoGen {
} }
internal void GenerateStaticVariableInitializers(TextGenerator writer) { 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); writer.WriteLine("{0}.{1} = pb::GeneratedRepeatExtension<{2}>.CreateInstance({0}.Descriptor.Extensions[{3}]);", scope, name, type, Descriptor.Index);
} else { } else {
writer.WriteLine("{0}.{1} = pb::GeneratedSingleExtension<{2}>.CreateInstance({0}.Descriptor.Extensions[{3}]);", scope, name, type, Descriptor.Index); 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 { ...@@ -88,5 +122,14 @@ namespace Google.ProtocolBuffers.ProtoGen {
internal void GenerateExtensionRegistrationCode(TextGenerator writer) { internal void GenerateExtensionRegistrationCode(TextGenerator writer) {
writer.WriteLine("registry.Add({0}.{1});", scope, name); 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 { ...@@ -42,6 +42,10 @@ namespace Google.ProtocolBuffers.ProtoGen {
: base(descriptor) { : 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) { private static bool AllPrintableAscii(string text) {
foreach (char c in text) { foreach (char c in text) {
if (c < 0x20 || c > 0x7e) { if (c < 0x20 || c > 0x7e) {
...@@ -51,6 +55,7 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -51,6 +55,7 @@ namespace Google.ProtocolBuffers.ProtoGen {
return true; return true;
} }
/// <remarks>Copy exists in ExtensionGenerator.cs</remarks>
protected string DefaultValue { protected string DefaultValue {
get { get {
string suffix = ""; string suffix = "";
...@@ -72,11 +77,30 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -72,11 +77,30 @@ namespace Google.ProtocolBuffers.ProtoGen {
case FieldType.UInt32: case FieldType.UInt32:
case FieldType.UInt64: case FieldType.UInt64:
case FieldType.Fixed32: case FieldType.Fixed32:
case FieldType.Fixed64: case FieldType.Fixed64:
{
// The simple Object.ToString converts using the current culture. // The simple Object.ToString converts using the current culture.
// We want to always use the invariant culture so it's predictable. // We want to always use the invariant culture so it's predictable.
IConvertible value = (IConvertible) Descriptor.DefaultValue; 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; return value.ToString(CultureInfo.InvariantCulture) + suffix;
}
case FieldType.Bool: case FieldType.Bool:
return (bool) Descriptor.DefaultValue ? "true" : "false"; return (bool) Descriptor.DefaultValue ? "true" : "false";
...@@ -84,6 +108,10 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -84,6 +108,10 @@ namespace Google.ProtocolBuffers.ProtoGen {
if (!Descriptor.HasDefaultValue) { if (!Descriptor.HasDefaultValue) {
return "pb::ByteString.Empty"; 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); return string.Format("(pb::ByteString) {0}.Descriptor.Fields[{1}].DefaultValue", GetClassName(Descriptor.ContainingType), Descriptor.Index);
case FieldType.String: case FieldType.String:
if (AllPrintableAscii(Descriptor.Proto.DefaultValue)) { if (AllPrintableAscii(Descriptor.Proto.DefaultValue)) {
...@@ -95,6 +123,10 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -95,6 +123,10 @@ namespace Google.ProtocolBuffers.ProtoGen {
.Replace("\"", "\\\"") .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); return string.Format("(string) {0}.Descriptor.Fields[{1}].DefaultValue", GetClassName(Descriptor.ContainingType), Descriptor.Index);
case FieldType.Enum: case FieldType.Enum:
return TypeName + "." + ((EnumValueDescriptor) Descriptor.DefaultValue).Name; return TypeName + "." + ((EnumValueDescriptor) Descriptor.DefaultValue).Name;
......
...@@ -38,11 +38,5 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -38,11 +38,5 @@ namespace Google.ProtocolBuffers.ProtoGen {
/// Helpers to resolve class names etc. /// Helpers to resolve class names etc.
/// </summary> /// </summary>
internal static class Helpers { 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 { ...@@ -41,5 +41,9 @@ namespace Google.ProtocolBuffers.ProtoGen {
void GenerateParsingCode(TextGenerator writer); void GenerateParsingCode(TextGenerator writer);
void GenerateSerializationCode(TextGenerator writer); void GenerateSerializationCode(TextGenerator writer);
void GenerateSerializedSizeCode(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 { ...@@ -125,5 +125,18 @@ namespace Google.ProtocolBuffers.ProtoGen {
MessageOrGroup, Number, PropertyName); MessageOrGroup, 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(\"{2}\", has{0}, {1}_, writer);", PropertyName, Name,
Descriptor.FieldType == FieldType.Group ? Descriptor.MessageType.Name : Descriptor.Name);
}
} }
} }
This diff is collapsed.
...@@ -103,5 +103,17 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -103,5 +103,17 @@ namespace Google.ProtocolBuffers.ProtoGen {
CapitalizedTypeName, Number, PropertyName); CapitalizedTypeName, 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);
}
} }
} }
...@@ -43,7 +43,7 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -43,7 +43,7 @@ namespace Google.ProtocolBuffers.ProtoGen {
} }
public void GenerateMembers(TextGenerator writer) { 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 int {0}MemoizedSerializedSize;", Name);
} }
writer.WriteLine("private pbc::PopsicleList<{0}> {1}_ = new pbc::PopsicleList<{0}>();", TypeName, Name); writer.WriteLine("private pbc::PopsicleList<{0}> {1}_ = new pbc::PopsicleList<{0}>();", TypeName, Name);
...@@ -114,10 +114,12 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -114,10 +114,12 @@ namespace Google.ProtocolBuffers.ProtoGen {
// TODO(jonskeet): Make a more efficient way of doing this // TODO(jonskeet): Make a more efficient way of doing this
writer.WriteLine("int rawValue = input.ReadEnum();"); writer.WriteLine("int rawValue = input.ReadEnum();");
writer.WriteLine("if (!global::System.Enum.IsDefined(typeof({0}), rawValue)) {{", TypeName); writer.WriteLine("if (!global::System.Enum.IsDefined(typeof({0}), rawValue)) {{", TypeName);
writer.WriteLine(" if (unknownFields == null) {"); // First unknown field - create builder now if (!UseLiteRuntime) {
writer.WriteLine(" unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);"); writer.WriteLine(" if (unknownFields == null) {"); // First unknown field - create builder now
writer.WriteLine(" }"); writer.WriteLine(" unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);");
writer.WriteLine(" unknownFields.MergeVarintField({0}, (ulong) rawValue);", Number); writer.WriteLine(" }");
writer.WriteLine(" unknownFields.MergeVarintField({0}, (ulong) rawValue);", Number);
}
writer.WriteLine("} else {"); writer.WriteLine("} else {");
writer.WriteLine(" Add{0}(({1}) rawValue);", PropertyName, TypeName); writer.WriteLine(" Add{0}(({1}) rawValue);", PropertyName, TypeName);
writer.WriteLine("}"); writer.WriteLine("}");
...@@ -173,5 +175,20 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -173,5 +175,20 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.Outdent(); writer.Outdent();
writer.WriteLine("}"); 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 { ...@@ -132,5 +132,22 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine(" size += pb::CodedOutputStream.Compute{0}Size({1}, element);", MessageOrGroup, Number); writer.WriteLine(" size += pb::CodedOutputStream.Compute{0}Size({1}, element);", MessageOrGroup, Number);
writer.WriteLine("}"); 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 { ...@@ -43,7 +43,7 @@ namespace Google.ProtocolBuffers.ProtoGen {
} }
public void GenerateMembers(TextGenerator writer) { 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 int {0}MemoizedSerializedSize;", Name);
} }
writer.WriteLine("private pbc::PopsicleList<{0}> {1}_ = new pbc::PopsicleList<{0}>();", TypeName, Name); writer.WriteLine("private pbc::PopsicleList<{0}> {1}_ = new pbc::PopsicleList<{0}>();", TypeName, Name);
...@@ -168,5 +168,20 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -168,5 +168,20 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.Outdent(); writer.Outdent();
writer.WriteLine("}"); 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 { ...@@ -40,8 +40,20 @@ namespace Google.ProtocolBuffers.ProtoGen {
private readonly T descriptor; private readonly T descriptor;
protected readonly bool OptimizeSpeed;
protected readonly bool OptimizeSize;
protected readonly bool UseLiteRuntime;
protected readonly string RuntimeSuffix;
protected SourceGeneratorBase(T descriptor) { protected SourceGeneratorBase(T descriptor) {
this.descriptor = 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 { protected T Descriptor {
......
...@@ -74,10 +74,6 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -74,10 +74,6 @@ namespace Google.ProtocolBuffers.ProtoGen {
return false; return false;
} }
public string UmbrellaClassName {
get { throw new NotImplementedException(); }
}
public void Generate(TextGenerator writer) { public void Generate(TextGenerator writer) {
WriteIntroduction(writer); WriteIntroduction(writer);
WriteExtensionRegistration(writer); WriteExtensionRegistration(writer);
...@@ -87,7 +83,11 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -87,7 +83,11 @@ namespace Google.ProtocolBuffers.ProtoGen {
new MessageGenerator(message).GenerateStaticVariables(writer); new MessageGenerator(message).GenerateStaticVariables(writer);
} }
writer.WriteLine("#endregion"); 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. // The class declaration either gets closed before or after the children are written.
if (!Descriptor.CSharpOptions.NestClasses) { if (!Descriptor.CSharpOptions.NestClasses) {
writer.Outdent(); writer.Outdent();
...@@ -113,9 +113,12 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -113,9 +113,12 @@ namespace Google.ProtocolBuffers.ProtoGen {
} }
private void WriteIntroduction(TextGenerator writer) { 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(); 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 != "") { if (Descriptor.CSharpOptions.Namespace != "") {
writer.WriteLine("namespace {0} {{", Descriptor.CSharpOptions.Namespace); writer.WriteLine("namespace {0} {{", Descriptor.CSharpOptions.Namespace);
...@@ -215,5 +218,24 @@ namespace Google.ProtocolBuffers.ProtoGen { ...@@ -215,5 +218,24 @@ namespace Google.ProtocolBuffers.ProtoGen {
writer.WriteLine("#endregion"); writer.WriteLine("#endregion");
writer.WriteLine(); 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();
}
} }
} }
This diff is collapsed.
...@@ -54,37 +54,37 @@ ...@@ -54,37 +54,37 @@
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug_Silverlight2|AnyCPU'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug_Silverlight2|AnyCPU'">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType> <DebugType>full</DebugType>
<Optimize>false</Optimize> <Optimize>false</Optimize>
<OutputPath>bin\Debug_Silverlight2\</OutputPath> <OutputPath>bin\Debug_Silverlight2\</OutputPath>
<DefineConstants>DEBUG;TRACE;SILVERLIGHT2</DefineConstants> <DefineConstants>DEBUG;TRACE;SILVERLIGHT2</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<NoStdLib>true</NoStdLib> <NoStdLib>true</NoStdLib>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release_Silverlight2|AnyCPU'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release_Silverlight2|AnyCPU'">
<DebugType>pdbonly</DebugType> <DebugType>pdbonly</DebugType>
<Optimize>true</Optimize> <Optimize>true</Optimize>
<OutputPath>bin\Release_Silverlight2\</OutputPath> <OutputPath>bin\Release_Silverlight2\</OutputPath>
<DefineConstants>TRACE;SILVERLIGHT2</DefineConstants> <DefineConstants>TRACE;SILVERLIGHT2</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<NoStdLib>true</NoStdLib> <NoStdLib>true</NoStdLib>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<Reference Include="nunit.framework, Version=2.2.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77"> <Reference Include="nunit.framework, Version=2.2.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77">
<SpecificVersion>False</SpecificVersion> <SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\nunit.framework.dll</HintPath> <HintPath>..\..\lib\NUnit 2.2.8.0\nunit.framework.dll</HintPath>
</Reference> </Reference>
<Reference Include="Rhino.Mocks, Version=3.5.0.2, Culture=neutral, PublicKeyToken=0b3305902db7183f, processorArchitecture=MSIL"> <Reference Include="Rhino.Mocks, Version=3.5.0.2, Culture=neutral, PublicKeyToken=0b3305902db7183f, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion> <SpecificVersion>False</SpecificVersion>
<HintPath>..\..\lib\Rhino.Mocks.dll</HintPath> <HintPath>..\..\lib\Rhino.Mocks.dll</HintPath>
</Reference> </Reference>
<Reference Include="mscorlib" /> <Reference Include="mscorlib" />
<Reference Include="System" /> <Reference Include="System" />
<Reference Include="System.Data" /> <Reference Include="System.Data" />
<Reference Include="System.Xml" /> <Reference Include="System.Xml" />
...@@ -99,6 +99,7 @@ ...@@ -99,6 +99,7 @@
<Compile Include="DescriptorsTest.cs" /> <Compile Include="DescriptorsTest.cs" />
<Compile Include="Descriptors\MessageDescriptorTest.cs" /> <Compile Include="Descriptors\MessageDescriptorTest.cs" />
<Compile Include="DynamicMessageTest.cs" /> <Compile Include="DynamicMessageTest.cs" />
<Compile Include="ExtendableMessageTest.cs" />
<Compile Include="GeneratedMessageTest.cs" /> <Compile Include="GeneratedMessageTest.cs" />
<Compile Include="MessageStreamIteratorTest.cs" /> <Compile Include="MessageStreamIteratorTest.cs" />
<Compile Include="MessageStreamWriterTest.cs" /> <Compile Include="MessageStreamWriterTest.cs" />
...@@ -111,8 +112,11 @@ ...@@ -111,8 +112,11 @@
<Compile Include="TestProtos\UnitTestCSharpOptionsProtoFile.cs" /> <Compile Include="TestProtos\UnitTestCSharpOptionsProtoFile.cs" />
<Compile Include="TestProtos\UnitTestCustomOptionsProtoFile.cs" /> <Compile Include="TestProtos\UnitTestCustomOptionsProtoFile.cs" />
<Compile Include="TestProtos\UnitTestEmbedOptimizeForProtoFile.cs" /> <Compile Include="TestProtos\UnitTestEmbedOptimizeForProtoFile.cs" />
<Compile Include="TestProtos\UnitTestEmptyProtoFile.cs" />
<Compile Include="TestProtos\UnitTestImportLiteProtoFile.cs" />
<Compile Include="TestProtos\UnitTestImportProtoFile.cs" /> <Compile Include="TestProtos\UnitTestImportProtoFile.cs" />
<Compile Include="TestProtos\UnitTestMessageSetProtoFile.cs" /> <Compile Include="TestProtos\UnitTestMessageSetProtoFile.cs" />
<Compile Include="TestProtos\UnitTestNoGenericServicesProtoFile.cs" />
<Compile Include="TestProtos\UnitTestOptimizeForProtoFile.cs" /> <Compile Include="TestProtos\UnitTestOptimizeForProtoFile.cs" />
<Compile Include="TestProtos\UnitTestProtoFile.cs" /> <Compile Include="TestProtos\UnitTestProtoFile.cs" />
<Compile Include="TestUtil.cs" /> <Compile Include="TestUtil.cs" />
......
...@@ -213,7 +213,7 @@ namespace Google.ProtocolBuffers { ...@@ -213,7 +213,7 @@ namespace Google.ProtocolBuffers {
ExtensionInfo extension = extensionRegistry[field.ContainingType, field.FieldNumber]; ExtensionInfo extension = extensionRegistry[field.ContainingType, field.FieldNumber];
Assert.IsNotNull(extension); Assert.IsNotNull(extension);
Assert.IsNotNull(extension.DefaultInstance); Assert.IsNotNull(extension.DefaultInstance);
return extension.DefaultInstance.WeakCreateBuilderForType(); return (IBuilder)extension.DefaultInstance.WeakCreateBuilderForType();
} }
} }
......
// 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 pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections; using pbc = global::Google.ProtocolBuffers.Collections;
......
// 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 pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections; using pbc = global::Google.ProtocolBuffers.Collections;
......
// 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
}
}
// 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
}
// 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 pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections; using pbc = global::Google.ProtocolBuffers.Collections;
......
// 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 pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections; using pbc = global::Google.ProtocolBuffers.Collections;
......
// 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 pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections; using pbc = global::Google.ProtocolBuffers.Collections;
......
 
Microsoft Visual Studio Solution File, Format Version 11.00 Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010 # 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}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProtocolBuffers", "ProtocolBuffers\ProtocolBuffers.csproj", "{6908BDCE-D925-43F3-94AC-A531E6DF2591}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProtocolBuffers.Test", "ProtocolBuffers.Test\ProtocolBuffers.Test.csproj", "{DD01ED24-3750-4567-9A23-1DB676A15610}" 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 ...@@ -17,13 +45,11 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProtoBench", "ProtoBench\Pr
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProtoDump", "ProtoDump\ProtoDump.csproj", "{D7282E99-2DC3-405B-946F-177DB2FD2AE2}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProtoDump", "ProtoDump\ProtoDump.csproj", "{D7282E99-2DC3-405B-946F-177DB2FD2AE2}"
EndProject EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "proto", "proto", "{1F896D5C-5FC2-4671-9216-781CB8187EC7}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProtocolBuffersLite", "ProtocolBuffers\ProtocolBuffersLite.csproj", "{6969BDCE-D925-43F3-94AC-A531E6DF2591}"
ProjectSection(SolutionItems) = preProject EndProject
..\protos\tutorial\addressbook.proto = ..\protos\tutorial\addressbook.proto Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProtocolBuffersLite.Test", "ProtocolBuffersLite.Test\ProtocolBuffersLite.Test.csproj", "{EE01ED24-3750-4567-9A23-1DB676A15610}"
..\protos\google\protobuf\csharp_options.proto = ..\protos\google\protobuf\csharp_options.proto EndProject
..\protos\google\protobuf\descriptor.proto = ..\protos\google\protobuf\descriptor.proto Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProtocolBuffersLiteMixed.Test", "ProtocolBuffersLite.Test\ProtocolBuffersLiteMixed.Test.csproj", "{EEFFED24-3750-4567-9A23-1DB676A15610}"
..\todo.txt = ..\todo.txt
EndProjectSection
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
...@@ -97,8 +123,35 @@ Global ...@@ -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_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.ActiveCfg = Release|Any CPU
{D7282E99-2DC3-405B-946F-177DB2FD2AE2}.Release|Any CPU.Build.0 = 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 EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
EndGlobalSection EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{C8D3015A-EA39-4F03-AEEC-3FF1F2087A12} = {1F896D5C-5FC2-4671-9216-781CB8187EC7}
EndGlobalSection
EndGlobal EndGlobal
This diff is collapsed.
#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 { ...@@ -42,7 +42,7 @@ namespace Google.ProtocolBuffers {
/// <summary> /// <summary>
/// Implementation of the non-generic IMessage interface as far as possible. /// Implementation of the non-generic IMessage interface as far as possible.
/// </summary> /// </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 TMessage : AbstractMessage<TMessage, TBuilder>
where TBuilder : AbstractBuilder<TMessage, TBuilder> { where TBuilder : AbstractBuilder<TMessage, TBuilder> {
/// <summary> /// <summary>
...@@ -59,24 +59,13 @@ namespace Google.ProtocolBuffers { ...@@ -59,24 +59,13 @@ namespace Google.ProtocolBuffers {
public abstract int GetRepeatedFieldCount(FieldDescriptor field); public abstract int GetRepeatedFieldCount(FieldDescriptor field);
public abstract object this[FieldDescriptor field, int index] { get; } public abstract object this[FieldDescriptor field, int index] { get; }
public abstract UnknownFieldSet UnknownFields { get; } public abstract UnknownFieldSet UnknownFields { get; }
public abstract TMessage DefaultInstanceForType { get; }
public abstract TBuilder CreateBuilderForType();
public abstract TBuilder ToBuilder();
#endregion #endregion
public IBuilder WeakCreateBuilderForType() {
return CreateBuilderForType();
}
public IBuilder WeakToBuilder() {
return ToBuilder();
}
public IMessage WeakDefaultInstanceForType { /// <summary>
get { return DefaultInstanceForType; } /// Returns true iff all required fields in the message and all embedded
} /// messages are set.
/// </summary>
public virtual bool IsInitialized { public override bool IsInitialized {
get { get {
// Check that all required fields are present. // Check that all required fields are present.
foreach (FieldDescriptor field in DescriptorForType.Fields) { foreach (FieldDescriptor field in DescriptorForType.Fields) {
...@@ -92,13 +81,13 @@ namespace Google.ProtocolBuffers { ...@@ -92,13 +81,13 @@ namespace Google.ProtocolBuffers {
if (field.IsRepeated) { if (field.IsRepeated) {
// We know it's an IList<T>, but not the exact type - so // We know it's an IList<T>, but not the exact type - so
// IEnumerable is the best we can do. (C# generics aren't covariant yet.) // IEnumerable 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) { if (!element.IsInitialized) {
return false; return false;
} }
} }
} else { } else {
if (!((IMessage)entry.Value).IsInitialized) { if (!((IMessageLite)entry.Value).IsInitialized) {
return false; return false;
} }
} }
...@@ -112,7 +101,23 @@ namespace Google.ProtocolBuffers { ...@@ -112,7 +101,23 @@ namespace Google.ProtocolBuffers {
return TextFormat.PrintToString(this); 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) { foreach (KeyValuePair<FieldDescriptor, object> entry in AllFields) {
FieldDescriptor field = entry.Key; FieldDescriptor field = entry.Key;
if (field.IsRepeated) { if (field.IsRepeated) {
...@@ -147,7 +152,11 @@ namespace Google.ProtocolBuffers { ...@@ -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 { get {
if (memoizedSize != null) { if (memoizedSize != null) {
return memoizedSize.Value; return memoizedSize.Value;
...@@ -188,33 +197,12 @@ namespace Google.ProtocolBuffers { ...@@ -188,33 +197,12 @@ namespace Google.ProtocolBuffers {
} }
} }
public ByteString ToByteString() { /// <summary>
ByteString.CodedBuilder output = new ByteString.CodedBuilder(SerializedSize); /// Compares the specified object with this message for equality.
WriteTo(output.CodedOutput); /// Returns true iff the given object is a message of the same type
return output.Build(); /// (as defined by DescriptorForType) and has identical values
} /// for all its fields.
/// </summary>
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();
}
public override bool Equals(object other) { public override bool Equals(object other) {
if (other == this) { if (other == this) {
return true; return true;
...@@ -226,6 +214,10 @@ namespace Google.ProtocolBuffers { ...@@ -226,6 +214,10 @@ namespace Google.ProtocolBuffers {
return Dictionaries.Equals(AllFields, otherMessage.AllFields) && UnknownFields.Equals(otherMessage.UnknownFields); 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() { public override int GetHashCode() {
int hash = 41; int hash = 41;
hash = (19 * hash) + DescriptorForType.GetHashCode(); hash = (19 * hash) + DescriptorForType.GetHashCode();
...@@ -233,5 +225,21 @@ namespace Google.ProtocolBuffers { ...@@ -233,5 +225,21 @@ namespace Google.ProtocolBuffers {
hash = (29 * hash) + UnknownFields.GetHashCode(); hash = (29 * hash) + UnknownFields.GetHashCode();
return hash; return hash;
} }
#region Explicit Members
IBuilder IMessage.WeakCreateBuilderForType() {
return CreateBuilderForType();
}
IBuilder IMessage.WeakToBuilder() {
return ToBuilder();
}
IMessage IMessage.WeakDefaultInstanceForType {
get { return DefaultInstanceForType; }
}
#endregion
} }
} }
#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 { ...@@ -78,6 +78,13 @@ namespace Google.ProtocolBuffers {
return (byte[])bytes.Clone(); 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> /// <summary>
/// Constructs a ByteString from the given array. The contents /// Constructs a ByteString from the given array. The contents
/// are copied, so further modifications to the array will not /// are copied, so further modifications to the array will not
......
...@@ -258,7 +258,7 @@ namespace Google.ProtocolBuffers { ...@@ -258,7 +258,7 @@ namespace Google.ProtocolBuffers {
/// <summary> /// <summary>
/// Reads a group field value from the stream. /// Reads a group field value from the stream.
/// </summary> /// </summary>
public void ReadGroup(int fieldNumber, IBuilder builder, public void ReadGroup(int fieldNumber, IBuilderLite builder,
ExtensionRegistry extensionRegistry) { ExtensionRegistry extensionRegistry) {
if (recursionDepth >= recursionLimit) { if (recursionDepth >= recursionLimit) {
throw InvalidProtocolBufferException.RecursionLimitExceeded(); throw InvalidProtocolBufferException.RecursionLimitExceeded();
...@@ -273,12 +273,14 @@ namespace Google.ProtocolBuffers { ...@@ -273,12 +273,14 @@ namespace Google.ProtocolBuffers {
/// Reads a group field value from the stream and merges it into the given /// Reads a group field value from the stream and merges it into the given
/// UnknownFieldSet. /// UnknownFieldSet.
/// </summary> /// </summary>
public void ReadUnknownGroup(int fieldNumber, UnknownFieldSet.Builder builder) { [Obsolete]
public void ReadUnknownGroup(int fieldNumber, IBuilderLite builder)
{
if (recursionDepth >= recursionLimit) { if (recursionDepth >= recursionLimit) {
throw InvalidProtocolBufferException.RecursionLimitExceeded(); throw InvalidProtocolBufferException.RecursionLimitExceeded();
} }
++recursionDepth; ++recursionDepth;
builder.MergeFrom(this); builder.WeakMergeFrom(this);
CheckLastTagWas(WireFormat.MakeTag(fieldNumber, WireFormat.WireType.EndGroup)); CheckLastTagWas(WireFormat.MakeTag(fieldNumber, WireFormat.WireType.EndGroup));
--recursionDepth; --recursionDepth;
} }
...@@ -286,7 +288,7 @@ namespace Google.ProtocolBuffers { ...@@ -286,7 +288,7 @@ namespace Google.ProtocolBuffers {
/// <summary> /// <summary>
/// Reads an embedded message field value from the stream. /// Reads an embedded message field value from the stream.
/// </summary> /// </summary>
public void ReadMessage(IBuilder builder, ExtensionRegistry extensionRegistry) { public void ReadMessage(IBuilderLite builder, ExtensionRegistry extensionRegistry) {
int length = (int) ReadRawVarint32(); int length = (int) ReadRawVarint32();
if (recursionDepth >= recursionLimit) { if (recursionDepth >= recursionLimit) {
throw InvalidProtocolBufferException.RecursionLimitExceeded(); throw InvalidProtocolBufferException.RecursionLimitExceeded();
...@@ -393,7 +395,6 @@ namespace Google.ProtocolBuffers { ...@@ -393,7 +395,6 @@ namespace Google.ProtocolBuffers {
throw new ArgumentOutOfRangeException("Invalid field type " + fieldType); throw new ArgumentOutOfRangeException("Invalid field type " + fieldType);
} }
} }
#endregion #endregion
#region Underlying reading primitives #region Underlying reading primitives
......
This diff is collapsed.
// 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 pb = global::Google.ProtocolBuffers;
using pbc = global::Google.ProtocolBuffers.Collections; using pbc = global::Google.ProtocolBuffers.Collections;
......
...@@ -37,7 +37,7 @@ namespace Google.ProtocolBuffers.Descriptors { ...@@ -37,7 +37,7 @@ namespace Google.ProtocolBuffers.Descriptors {
/// <summary> /// <summary>
/// Descriptor for an enum type in a .proto file. /// Descriptor for an enum type in a .proto file.
/// </summary> /// </summary>
public sealed class EnumDescriptor : IndexedDescriptorBase<EnumDescriptorProto, EnumOptions> { public sealed class EnumDescriptor : IndexedDescriptorBase<EnumDescriptorProto, EnumOptions>, IEnumLiteMap<EnumValueDescriptor> {
private readonly MessageDescriptor containingType; private readonly MessageDescriptor containingType;
private readonly IList<EnumValueDescriptor> values; private readonly IList<EnumValueDescriptor> values;
...@@ -72,14 +72,24 @@ namespace Google.ProtocolBuffers.Descriptors { ...@@ -72,14 +72,24 @@ namespace Google.ProtocolBuffers.Descriptors {
get { return values; } 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> /// <summary>
/// Finds an enum value by number. If multiple enum values have the /// Finds an enum value by number. If multiple enum values have the
/// same number, this returns the first defined value with that number. /// same number, this returns the first defined value with that number.
/// </summary> /// </summary>
internal EnumValueDescriptor FindValueByNumber(int number) { public EnumValueDescriptor FindValueByNumber(int number) {
return File.DescriptorPool.FindEnumValueByNumber(this, number); return File.DescriptorPool.FindEnumValueByNumber(this, number);
} }
IEnumLite IEnumLiteMap.FindValueByNumber(int number) {
return FindValueByNumber(number);
}
/// <summary> /// <summary>
/// Finds an enum value by name. /// Finds an enum value by name.
/// </summary> /// </summary>
......
...@@ -36,7 +36,7 @@ namespace Google.ProtocolBuffers.Descriptors { ...@@ -36,7 +36,7 @@ namespace Google.ProtocolBuffers.Descriptors {
/// <summary> /// <summary>
/// Descriptor for a single enum value within an enum in a .proto file. /// Descriptor for a single enum value within an enum in a .proto file.
/// </summary> /// </summary>
public sealed class EnumValueDescriptor : IndexedDescriptorBase<EnumValueDescriptorProto, EnumValueOptions> { public sealed class EnumValueDescriptor : IndexedDescriptorBase<EnumValueDescriptorProto, EnumValueOptions>, IEnumLite {
private readonly EnumDescriptor enumDescriptor; private readonly EnumDescriptor enumDescriptor;
......
...@@ -40,7 +40,7 @@ namespace Google.ProtocolBuffers.Descriptors { ...@@ -40,7 +40,7 @@ namespace Google.ProtocolBuffers.Descriptors {
/// <summary> /// <summary>
/// Descriptor for a field or extension within a message in a .proto file. /// Descriptor for a field or extension within a message in a .proto file.
/// </summary> /// </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 readonly MessageDescriptor extensionScope;
private EnumDescriptor enumType; private EnumDescriptor enumType;
...@@ -299,9 +299,26 @@ namespace Google.ProtocolBuffers.Descriptors { ...@@ -299,9 +299,26 @@ namespace Google.ProtocolBuffers.Descriptors {
} }
return FieldNumber - other.FieldNumber; return FieldNumber - other.FieldNumber;
} }
/// <summary> /// <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. /// For enum fields, returns the field's type.
/// </summary> /// </summary>
public EnumDescriptor EnumType { public EnumDescriptor EnumType {
......
...@@ -30,6 +30,8 @@ ...@@ -30,6 +30,8 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System; using System;
using System.Collections.Generic;
using Google.ProtocolBuffers.Collections;
namespace Google.ProtocolBuffers.Descriptors { namespace Google.ProtocolBuffers.Descriptors {
...@@ -46,5 +48,29 @@ namespace Google.ProtocolBuffers.Descriptors { ...@@ -46,5 +48,29 @@ namespace Google.ProtocolBuffers.Descriptors {
internal MappedType MappedType { get; private set; } internal MappedType MappedType { get; private set; }
internal WireFormat.WireType WireType { 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 { ...@@ -180,7 +180,7 @@ namespace Google.ProtocolBuffers {
} }
public override IDictionary<FieldDescriptor, object> AllFields { public override IDictionary<FieldDescriptor, object> AllFields {
get { return fields.AllFields; } get { return fields.AllFieldDescriptors; }
} }
public override bool HasField(FieldDescriptor field) { public override bool HasField(FieldDescriptor field) {
...@@ -216,7 +216,7 @@ namespace Google.ProtocolBuffers { ...@@ -216,7 +216,7 @@ namespace Google.ProtocolBuffers {
} }
public bool Initialized { public bool Initialized {
get { return fields.IsInitializedWithRespectTo(type); } get { return fields.IsInitializedWithRespectTo(type.Fields); }
} }
public override void WriteTo(CodedOutputStream output) { public override void WriteTo(CodedOutputStream output) {
...@@ -295,7 +295,8 @@ namespace Google.ProtocolBuffers { ...@@ -295,7 +295,8 @@ namespace Google.ProtocolBuffers {
} }
public override Builder MergeFrom(DynamicMessage other) { public override Builder MergeFrom(DynamicMessage other) {
return MergeFrom((IMessage)other); IMessage downcast = other;
return MergeFrom(downcast);
} }
public override DynamicMessage Build() { public override DynamicMessage Build() {
...@@ -335,7 +336,7 @@ namespace Google.ProtocolBuffers { ...@@ -335,7 +336,7 @@ namespace Google.ProtocolBuffers {
} }
public override bool IsInitialized { public override bool IsInitialized {
get { return fields.IsInitializedWithRespectTo(type); } get { return fields.IsInitializedWithRespectTo(type.Fields); }
} }
public override Builder MergeFrom(CodedInputStream input, ExtensionRegistry extensionRegistry) { public override Builder MergeFrom(CodedInputStream input, ExtensionRegistry extensionRegistry) {
...@@ -354,7 +355,7 @@ namespace Google.ProtocolBuffers { ...@@ -354,7 +355,7 @@ namespace Google.ProtocolBuffers {
} }
public override IDictionary<FieldDescriptor, object> AllFields { public override IDictionary<FieldDescriptor, object> AllFields {
get { return fields.AllFields; } get { return fields.AllFieldDescriptors; }
} }
public override IBuilder CreateBuilderForField(FieldDescriptor field) { public override IBuilder CreateBuilderForField(FieldDescriptor field) {
......
#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 { ...@@ -94,21 +94,21 @@ namespace Google.ProtocolBuffers {
/// <summary> /// <summary>
/// Appends a value to a repeated extension. /// Appends a value to a repeated extension.
/// </summary> /// </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; ExtendableMessage<TMessage, TBuilder> message = MessageBeingBuilt;
message.VerifyExtensionContainingType(extension); message.VerifyExtensionContainingType(extension);
message.Extensions.AddRepeatedField(extension.Descriptor, extension.SingularToReflectionType(value)); message.Extensions.AddRepeatedField(extension.Descriptor, extension.SingularToReflectionType(value));
return this; return ThisBuilder;
} }
/// <summary> /// <summary>
/// Clears an extension. /// Clears an extension.
/// </summary> /// </summary>
public ExtendableBuilder<TMessage, TBuilder> ClearExtension<TExtension>(GeneratedExtensionBase<TExtension> extension) { public TBuilder ClearExtension<TExtension>(GeneratedExtensionBase<TExtension> extension) {
ExtendableMessage<TMessage, TBuilder> message = MessageBeingBuilt; ExtendableMessage<TMessage, TBuilder> message = MessageBeingBuilt;
message.VerifyExtensionContainingType(extension); message.VerifyExtensionContainingType(extension);
message.Extensions.ClearField(extension.Descriptor); message.Extensions.ClearField(extension.Descriptor);
return this; return ThisBuilder;
} }
/// <summary> /// <summary>
......
This diff is collapsed.
...@@ -102,8 +102,8 @@ namespace Google.ProtocolBuffers { ...@@ -102,8 +102,8 @@ namespace Google.ProtocolBuffers {
public override IDictionary<FieldDescriptor, object> AllFields { public override IDictionary<FieldDescriptor, object> AllFields {
get { get {
IDictionary<FieldDescriptor, object> result = GetMutableFieldMap(); IDictionary<FieldDescriptor, object> result = GetMutableFieldMap();
foreach(KeyValuePair<FieldDescriptor, object> entry in extensions.AllFields) { foreach(KeyValuePair<IFieldDescriptorLite, object> entry in extensions.AllFields) {
result[entry.Key] = entry.Value; result[(FieldDescriptor)entry.Key] = entry.Value;
} }
return Dictionaries.AsReadOnly(result); return Dictionaries.AsReadOnly(result);
} }
...@@ -173,9 +173,9 @@ namespace Google.ProtocolBuffers { ...@@ -173,9 +173,9 @@ namespace Google.ProtocolBuffers {
/// TODO(jonskeet): See if we can improve this in terms of readability. /// TODO(jonskeet): See if we can improve this in terms of readability.
/// </summary> /// </summary>
protected class ExtensionWriter { protected class ExtensionWriter {
readonly IEnumerator<KeyValuePair<FieldDescriptor, object>> iterator; readonly IEnumerator<KeyValuePair<IFieldDescriptorLite, object>> iterator;
readonly FieldSet extensions; readonly FieldSet extensions;
KeyValuePair<FieldDescriptor, object>? next = null; KeyValuePair<IFieldDescriptorLite, object>? next = null;
internal ExtensionWriter(ExtendableMessage<TMessage, TBuilder> message) { internal ExtensionWriter(ExtendableMessage<TMessage, TBuilder> message) {
extensions = message.extensions; extensions = message.extensions;
......
This diff is collapsed.
...@@ -36,24 +36,42 @@ using Google.ProtocolBuffers.Descriptors; ...@@ -36,24 +36,42 @@ using Google.ProtocolBuffers.Descriptors;
namespace Google.ProtocolBuffers namespace Google.ProtocolBuffers
{ {
public sealed class ExtensionInfo { public sealed class ExtensionInfo : IGeneratedExtensionLite {
/// <summary> /// <summary>
/// The extension's descriptor /// The extension's descriptor
/// </summary> /// </summary>
public FieldDescriptor Descriptor { get; private set; } 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, /// A default instance of the extensions's type, if it has a message type,
/// or null otherwise. /// or null otherwise.
/// </summary> /// </summary>
public IMessage DefaultInstance { get; private set; } public IMessageLite DefaultInstance { get; private set; }
internal ExtensionInfo(FieldDescriptor descriptor) : this(descriptor, null) { internal ExtensionInfo(FieldDescriptor descriptor) : this(descriptor, null) {
} }
internal ExtensionInfo(FieldDescriptor descriptor, IMessage defaultInstance) { internal ExtensionInfo(FieldDescriptor descriptor, IMessageLite defaultInstance) {
Descriptor = descriptor; Descriptor = descriptor;
DefaultInstance = defaultInstance; 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
} }
} }
\ No newline at end of file
...@@ -88,23 +88,20 @@ namespace Google.ProtocolBuffers { ...@@ -88,23 +88,20 @@ namespace Google.ProtocolBuffers {
/// could take advantage of this to inject a mutable object into a message /// could take advantage of this to inject a mutable object into a message
/// belonging to privileged code and create mischief.</para> /// belonging to privileged code and create mischief.</para>
/// </remarks> /// </remarks>
public sealed class ExtensionRegistry { public sealed partial class ExtensionRegistry {
#if !LITE
private static readonly ExtensionRegistry empty = new ExtensionRegistry( private static readonly ExtensionRegistry empty = new ExtensionRegistry(
new Dictionary<string, ExtensionInfo>(), new Dictionary<string, ExtensionInfo>(),
new Dictionary<DescriptorIntPair, ExtensionInfo>(), new Dictionary<ExtensionIntPair, IGeneratedExtensionLite>(),
true); true);
private readonly IDictionary<string, ExtensionInfo> extensionsByName; private readonly IDictionary<string, ExtensionInfo> extensionsByName;
private readonly IDictionary<DescriptorIntPair, ExtensionInfo> extensionsByNumber;
private readonly bool readOnly;
private ExtensionRegistry(IDictionary<String, ExtensionInfo> extensionsByName, private ExtensionRegistry(IDictionary<String, ExtensionInfo> extensionsByName,
IDictionary<DescriptorIntPair, ExtensionInfo> extensionsByNumber, IDictionary<ExtensionIntPair, IGeneratedExtensionLite> extensionsByNumber,
bool readOnly) { bool readOnly)
: this(extensionsByNumber, readOnly) {
this.extensionsByName = extensionsByName; this.extensionsByName = extensionsByName;
this.extensionsByNumber = extensionsByNumber;
this.readOnly = readOnly;
} }
/// <summary> /// <summary>
...@@ -112,19 +109,13 @@ namespace Google.ProtocolBuffers { ...@@ -112,19 +109,13 @@ namespace Google.ProtocolBuffers {
/// </summary> /// </summary>
public static ExtensionRegistry CreateInstance() { public static ExtensionRegistry CreateInstance() {
return new ExtensionRegistry(new Dictionary<string, ExtensionInfo>(), return new ExtensionRegistry(new Dictionary<string, ExtensionInfo>(),
new Dictionary<DescriptorIntPair, ExtensionInfo>(), false); new Dictionary<ExtensionIntPair, IGeneratedExtensionLite>(), false);
}
/// <summary>
/// Get the unmodifiable singleton empty instance.
/// </summary>
public static ExtensionRegistry Empty {
get { return empty; }
} }
public ExtensionRegistry AsReadOnly() { public ExtensionRegistry AsReadOnly() {
return new ExtensionRegistry(extensionsByName, extensionsByNumber, true); return new ExtensionRegistry(extensionsByName, extensionsByNumber, true);
} }
#endif
/// <summary> /// <summary>
/// Finds an extension by fully-qualified field name, in the /// Finds an extension by fully-qualified field name, in the
...@@ -146,9 +137,9 @@ namespace Google.ProtocolBuffers { ...@@ -146,9 +137,9 @@ namespace Google.ProtocolBuffers {
/// </summary> /// </summary>
public ExtensionInfo this[MessageDescriptor containingType, int fieldNumber] { public ExtensionInfo this[MessageDescriptor containingType, int fieldNumber] {
get { get {
ExtensionInfo ret; IGeneratedExtensionLite ret;
extensionsByNumber.TryGetValue(new DescriptorIntPair(containingType, fieldNumber), out ret); extensionsByNumber.TryGetValue(new ExtensionIntPair(containingType, fieldNumber), out ret);
return ret; return ret as ExtensionInfo;
} }
} }
...@@ -198,7 +189,7 @@ namespace Google.ProtocolBuffers { ...@@ -198,7 +189,7 @@ namespace Google.ProtocolBuffers {
} }
extensionsByName[extension.Descriptor.FullName] = extension; extensionsByName[extension.Descriptor.FullName] = extension;
extensionsByNumber[new DescriptorIntPair(extension.Descriptor.ContainingType, extensionsByNumber[new ExtensionIntPair(extension.Descriptor.ContainingType,
extension.Descriptor.FieldNumber)] = extension; extension.Descriptor.FieldNumber)] = extension;
FieldDescriptor field = extension.Descriptor; FieldDescriptor field = extension.Descriptor;
...@@ -212,34 +203,5 @@ namespace Google.ProtocolBuffers { ...@@ -212,34 +203,5 @@ namespace Google.ProtocolBuffers {
extensionsByName[field.MessageType.FullName] = extension; 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;
}
}
} }
} }
This diff is collapsed.
...@@ -71,7 +71,7 @@ namespace Google.ProtocolBuffers.FieldAccess { ...@@ -71,7 +71,7 @@ namespace Google.ProtocolBuffers.FieldAccess {
} }
// No... so let's create a builder of the right type, and merge the value in. // 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(); return CreateBuilder().WeakMergeFrom(message).WeakBuild();
} }
......
...@@ -67,7 +67,7 @@ namespace Google.ProtocolBuffers.FieldAccess { ...@@ -67,7 +67,7 @@ namespace Google.ProtocolBuffers.FieldAccess {
} }
// No... so let's create a builder of the right type, and merge the value in. // 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(); return CreateBuilder().WeakMergeFrom(message).WeakBuild();
} }
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment