From f52426827e4d5e8da7d205af538799740b5199b9 Mon Sep 17 00:00:00 2001 From: Jon Skeet Date: Fri, 5 Jun 2015 20:44:05 +0100 Subject: First stab at new proto3-only code generator --- src/google/protobuf/compiler/csharp/csharp_enum.cc | 2 +- .../protobuf/compiler/csharp/csharp_enum_field.cc | 49 +- .../protobuf/compiler/csharp/csharp_extension.cc | 184 ----- .../protobuf/compiler/csharp/csharp_extension.h | 78 -- .../protobuf/compiler/csharp/csharp_field_base.cc | 37 +- .../protobuf/compiler/csharp/csharp_field_base.h | 5 - .../protobuf/compiler/csharp/csharp_message.cc | 855 ++++----------------- .../protobuf/compiler/csharp/csharp_message.h | 14 +- .../compiler/csharp/csharp_message_field.cc | 231 +----- .../compiler/csharp/csharp_message_field.h | 6 - .../compiler/csharp/csharp_primitive_field.cc | 177 +---- .../compiler/csharp/csharp_primitive_field.h | 9 +- .../compiler/csharp/csharp_repeated_enum_field.cc | 131 +--- .../compiler/csharp/csharp_repeated_enum_field.h | 6 +- .../csharp/csharp_repeated_message_field.cc | 120 +-- .../csharp/csharp_repeated_message_field.h | 4 - .../csharp/csharp_repeated_primitive_field.cc | 119 +-- .../csharp/csharp_repeated_primitive_field.h | 4 - .../csharp/csharp_source_generator_base.cc | 8 - .../compiler/csharp/csharp_source_generator_base.h | 17 - .../compiler/csharp/csharp_umbrella_class.cc | 88 +-- .../compiler/csharp/csharp_umbrella_class.h | 7 - .../protobuf/compiler/csharp/csharp_writer.cc | 136 ---- .../protobuf/compiler/csharp/csharp_writer.h | 93 --- 24 files changed, 294 insertions(+), 2086 deletions(-) delete mode 100644 src/google/protobuf/compiler/csharp/csharp_extension.cc delete mode 100644 src/google/protobuf/compiler/csharp/csharp_extension.h delete mode 100644 src/google/protobuf/compiler/csharp/csharp_writer.cc delete mode 100644 src/google/protobuf/compiler/csharp/csharp_writer.h (limited to 'src/google') diff --git a/src/google/protobuf/compiler/csharp/csharp_enum.cc b/src/google/protobuf/compiler/csharp/csharp_enum.cc index 0e8f9836..d511bba3 100644 --- a/src/google/protobuf/compiler/csharp/csharp_enum.cc +++ b/src/google/protobuf/compiler/csharp/csharp_enum.cc @@ -58,7 +58,7 @@ EnumGenerator::~EnumGenerator() { void EnumGenerator::Generate(io::Printer* printer) { WriteGeneratedCodeAttributes(printer); - printer->Print("$access_level$ enum $name$ {\n", + printer->Print("$access_level$ enum $name$ : long {\n", "access_level", class_access_level(), "name", descriptor_->name()); printer->Indent(); diff --git a/src/google/protobuf/compiler/csharp/csharp_enum_field.cc b/src/google/protobuf/compiler/csharp/csharp_enum_field.cc index 51a95b9f..8865702d 100644 --- a/src/google/protobuf/compiler/csharp/csharp_enum_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_enum_field.cc @@ -55,36 +55,22 @@ EnumFieldGenerator::~EnumFieldGenerator() { void EnumFieldGenerator::GenerateParsingCode(io::Printer* printer) { printer->Print(variables_, - "object unknown;\n" - "if(input.ReadEnum(ref result.$name$_, out unknown)) {\n"); - if (SupportFieldPresence(descriptor_->file())) { - printer->Print(variables_, - " result.has$property_name$ = true;\n"); - } - printer->Print("} else if(unknown is int) {\n"); - if (!use_lite_runtime()) { - printer->Print(variables_, - " if (unknownFields == null) {\n" // First unknown field - create builder now - " unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);\n" - " }\n" - " unknownFields.MergeVarintField($number$, (ulong)(int)unknown);\n"); - } - printer->Print("}\n"); + "input.ReadEnum(ref $name$_);\n"); } void EnumFieldGenerator::GenerateSerializationCode(io::Printer* printer) { printer->Print(variables_, - "if ($has_property_check$) {\n" - " output.WriteEnum($number$, field_names[$field_ordinal$], (int) $property_name$, $property_name$);\n" - "}\n"); + "if ($has_property_check$) {\n" + " output.WriteEnum($number$, fieldNames[$field_ordinal$], (long) $property_name$, $property_name$);\n" + "}\n"); } void EnumFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { printer->Print( - variables_, - "if ($has_property_check$) {\n" - " size += pb::CodedOutputStream.ComputeEnumSize($number$, (int) $property_name$);\n" - "}\n"); + variables_, + "if ($has_property_check$) {\n" + " size += pb::CodedOutputStream.ComputeEnumSize($number$, (long) $property_name$);\n" + "}\n"); } EnumOneofFieldGenerator::EnumOneofFieldGenerator(const FieldDescriptor* descriptor, @@ -96,30 +82,21 @@ EnumOneofFieldGenerator::~EnumOneofFieldGenerator() { } void EnumOneofFieldGenerator::GenerateParsingCode(io::Printer* printer) { + // TODO(jonskeet): What about if we read the default value? printer->Print( variables_, - "object unknown;\n" "$type_name$ enumValue = $default_value$;\n" - "if(input.ReadEnum(ref enumValue, out unknown)) {\n" + "if(input.ReadEnum(ref enumValue)) {\n" " result.$oneof_name$_ = enumValue;\n" " result.$oneof_name$Case_ = $oneof_property_name$OneofCase.$property_name$;\n" - "} else if(unknown is int) {\n"); - if (!use_lite_runtime()) { - printer->Print( - variables_, - " if (unknownFields == null) {\n" // First unknown field - create builder now - " unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);\n" - " }\n" - " unknownFields.MergeVarintField($number$, (ulong)(int)unknown);\n"); - } - printer->Print("}\n"); + "}\n"); } void EnumOneofFieldGenerator::GenerateSerializationCode(io::Printer* printer) { printer->Print( variables_, "if ($has_property_check$) {\n" - " output.WriteEnum($number$, field_names[$field_ordinal$], (int) $property_name$, $property_name$);\n" + " output.WriteEnum($number$, fieldNames[$field_ordinal$], (long) $property_name$, $property_name$);\n" "}\n"); } @@ -127,7 +104,7 @@ void EnumOneofFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { printer->Print( variables_, "if ($has_property_check$) {\n" - " size += pb::CodedOutputStream.ComputeEnumSize($number$, (int) $property_name$);\n" + " size += pb::CodedOutputStream.ComputeEnumSize($number$, (long) $property_name$);\n" "}\n"); } diff --git a/src/google/protobuf/compiler/csharp/csharp_extension.cc b/src/google/protobuf/compiler/csharp/csharp_extension.cc deleted file mode 100644 index 8b665ae4..00000000 --- a/src/google/protobuf/compiler/csharp/csharp_extension.cc +++ /dev/null @@ -1,184 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// 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. - -#include - -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -using google::protobuf::internal::scoped_ptr; - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -ExtensionGenerator::ExtensionGenerator(const FieldDescriptor* descriptor) - : FieldGeneratorBase(descriptor, 0) { - if (descriptor_->extension_scope()) { - variables_["scope"] = GetClassName(descriptor_->extension_scope()); - } else { - variables_["scope"] = GetFullUmbrellaClassName(descriptor_->file()); - } - variables_["extends"] = GetClassName(descriptor_->containing_type()); - variables_["capitalized_type_name"] = capitalized_type_name(); - variables_["full_name"] = descriptor_->full_name(); - variables_["access_level"] = class_access_level(); - variables_["index"] = SimpleItoa(descriptor_->index()); - variables_["property_name"] = property_name(); - variables_["type_name"] = type_name(); - if (use_lite_runtime()) { - variables_["generated_extension"] = descriptor_->is_repeated() ? - "GeneratedRepeatExtensionLite" : "GeneratedExtensionLite"; - } else { - variables_["generated_extension"] = descriptor_->is_repeated() ? - "GeneratedRepeatExtension" : "GeneratedExtension"; - } -} - -ExtensionGenerator::~ExtensionGenerator() { -} - -void ExtensionGenerator::Generate(io::Printer* printer) { - printer->Print( - "public const int $constant_name$ = $number$;\n", - "constant_name", GetFieldConstantName(descriptor_), - "number", SimpleItoa(descriptor_->number())); - - if (use_lite_runtime()) { - // TODO(jtattermusch): include the following check - //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."); - //} - - printer->Print( - variables_, - "$access_level$ static pb::$generated_extension$<$extends$, $type_name$> $property_name$;\n"); - } else if (descriptor_->is_repeated()) { - printer->Print( - variables_, - "$access_level$ static pb::GeneratedExtensionBase> $property_name$;\n"); - } else { - printer->Print( - variables_, - "$access_level$ static pb::GeneratedExtensionBase<$type_name$> $property_name$;\n"); - } -} - -void ExtensionGenerator::GenerateStaticVariableInitializers(io::Printer* printer) { - if (use_lite_runtime()) { - printer->Print( - variables_, - "$scope$.$property_name$ = \n"); - printer->Indent(); - printer->Print( - variables_, - "new pb::$generated_extension$<$extends$, $type_name$>(\n"); - printer->Indent(); - printer->Print( - variables_, - "\"$full_name$\",\n" - "$extends$.DefaultInstance,\n"); - if (!descriptor_->is_repeated()) { - std::string default_val; - if (descriptor_->has_default_value()) { - default_val = default_value(); - } else { - default_val = is_nullable_type() ? "null" : ("default(" + type_name() + ")"); - } - printer->Print("$default_val$,\n", "default_val", default_val); - } - printer->Print( - "$message_val$,\n", - "message_val", - (GetCSharpType(descriptor_->type()) == CSHARPTYPE_MESSAGE) ? - type_name() + ".DefaultInstance" : "null"); - printer->Print( - "$enum_val$,\n", - "enum_val", - (GetCSharpType(descriptor_->type()) == CSHARPTYPE_ENUM) ? - "new EnumLiteMap<" + type_name() + ">()" : "null"); - printer->Print( - variables_, - "$scope$.$property_name$FieldNumber,\n" - "pbd::FieldType.$capitalized_type_name$"); - if (descriptor_->is_repeated()) { - printer->Print( - ",\n" - "$is_packed$", - "is_packed", descriptor_->is_packed() ? "true" : "false"); - } - printer->Outdent(); - printer->Print(");\n"); - printer->Outdent(); - } - else if (descriptor_->is_repeated()) - { - printer->Print( - variables_, - "$scope$.$property_name$ = pb::GeneratedRepeatExtension<$type_name$>.CreateInstance($scope$.Descriptor.Extensions[$index$]);\n"); - } - else - { - printer->Print( - variables_, - "$scope$.$property_name$ = pb::GeneratedSingleExtension<$type_name$>.CreateInstance($scope$.Descriptor.Extensions[$index$]);\n"); - } -} - -void ExtensionGenerator::GenerateExtensionRegistrationCode(io::Printer* printer) { - printer->Print( - variables_, - "registry.Add($scope$.$property_name$);\n"); -} - -void ExtensionGenerator::WriteHash(io::Printer* printer) { -} - -void ExtensionGenerator::WriteEquals(io::Printer* printer) { -} - -void ExtensionGenerator::WriteToString(io::Printer* printer) { -} - -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/src/google/protobuf/compiler/csharp/csharp_extension.h b/src/google/protobuf/compiler/csharp/csharp_extension.h deleted file mode 100644 index f251a21c..00000000 --- a/src/google/protobuf/compiler/csharp/csharp_extension.h +++ /dev/null @@ -1,78 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// 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. - -#ifndef GOOGLE_PROTOBUF_COMPILER_CSHARP_EXTENSION_H__ -#define GOOGLE_PROTOBUF_COMPILER_CSHARP_EXTENSION_H__ - -#include - -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -class ExtensionGenerator : public FieldGeneratorBase { - public: - ExtensionGenerator(const FieldDescriptor* descriptor); - ~ExtensionGenerator(); - - void GenerateStaticVariableInitializers(io::Printer* printer); - void GenerateExtensionRegistrationCode(io::Printer* printer); - void Generate(io::Printer* printer); - - virtual void WriteHash(io::Printer* printer); - virtual void WriteEquals(io::Printer* printer); - virtual void WriteToString(io::Printer* printer); - - virtual void GenerateMembers(io::Printer* printer) {}; - virtual void GenerateBuilderMembers(io::Printer* printer) {}; - virtual void GenerateMergingCode(io::Printer* printer) {}; - virtual void GenerateBuildingCode(io::Printer* printer) {}; - virtual void GenerateParsingCode(io::Printer* printer) {}; - virtual void GenerateSerializationCode(io::Printer* printer) {}; - virtual void GenerateSerializedSizeCode(io::Printer* printer) {}; - - private: - std::string scope_; - std::string extends_; - - GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(ExtensionGenerator); -}; - -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google - -#endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_EXTENSION_H__ - diff --git a/src/google/protobuf/compiler/csharp/csharp_field_base.cc b/src/google/protobuf/compiler/csharp/csharp_field_base.cc index c3ce426b..367e54c2 100644 --- a/src/google/protobuf/compiler/csharp/csharp_field_base.cc +++ b/src/google/protobuf/compiler/csharp/csharp_field_base.cc @@ -263,37 +263,13 @@ bool AllPrintableAscii(const std::string& text) { } std::string FieldGeneratorBase::GetStringDefaultValueInternal() { - if (!descriptor_->has_default_value()) { - return "\"\""; - } - if (AllPrintableAscii(descriptor_->default_value_string())) { - // All chars are ASCII and printable. In this case we only - // need to escape quotes and backslashes. - std::string temp = descriptor_->default_value_string(); - temp = StringReplace(temp, "\\", "\\\\", true); - temp = StringReplace(temp, "'", "\\'", true); - temp = StringReplace(temp, "\"", "\\\"", true); - return "\"" + temp + "\""; - } - if (use_lite_runtime()) { - return "pb::ByteString.FromBase64(\"" - + StringToBase64(descriptor_->default_value_string()) - + "\").ToStringUtf8()"; - } - return "(string) " + GetClassName(descriptor_->containing_type()) - + ".Descriptor.Fields[" + SimpleItoa(descriptor_->index()) - + "].DefaultValue"; + // No other default values needed for proto3... + return "\"\""; } std::string FieldGeneratorBase::GetBytesDefaultValueInternal() { - if (!descriptor_->has_default_value()) { - return "pb::ByteString.Empty"; - } - if (use_lite_runtime()) { - return "pb::ByteString.FromBase64(\"" + StringToBase64(descriptor_->default_value_string()) + "\")"; - } - return "(pb::ByteString) "+ GetClassName(descriptor_->containing_type()) + - ".Descriptor.Fields[" + SimpleItoa(descriptor_->index()) + "].DefaultValue"; + // No other default values needed for proto3... + return "pb::ByteString.Empty"; } std::string FieldGeneratorBase::default_value() { @@ -365,11 +341,6 @@ std::string FieldGeneratorBase::number() { return SimpleItoa(descriptor_->number()); } -std::string FieldGeneratorBase::message_or_group() { - return - (descriptor_->type() == FieldDescriptor::TYPE_GROUP) ? "Group" : "Message"; -} - std::string FieldGeneratorBase::capitalized_type_name() { switch (descriptor_->type()) { case FieldDescriptor::TYPE_ENUM: diff --git a/src/google/protobuf/compiler/csharp/csharp_field_base.h b/src/google/protobuf/compiler/csharp/csharp_field_base.h index b1570587..1b044a49 100644 --- a/src/google/protobuf/compiler/csharp/csharp_field_base.h +++ b/src/google/protobuf/compiler/csharp/csharp_field_base.h @@ -42,17 +42,13 @@ namespace protobuf { namespace compiler { namespace csharp { -class Writer; - class FieldGeneratorBase : public SourceGeneratorBase { public: FieldGeneratorBase(const FieldDescriptor* descriptor, int fieldOrdinal); ~FieldGeneratorBase(); virtual void GenerateMembers(io::Printer* printer) = 0; - virtual void GenerateBuilderMembers(io::Printer* printer) = 0; virtual void GenerateMergingCode(io::Printer* printer) = 0; - virtual void GenerateBuildingCode(io::Printer* printer) = 0; virtual void GenerateParsingCode(io::Printer* printer) = 0; virtual void GenerateSerializationCode(io::Printer* printer) = 0; virtual void GenerateSerializedSizeCode(io::Printer* printer) = 0; @@ -82,7 +78,6 @@ class FieldGeneratorBase : public SourceGeneratorBase { bool is_nullable_type(); std::string default_value(); std::string number(); - std::string message_or_group(); std::string capitalized_type_name(); std::string field_ordinal(); diff --git a/src/google/protobuf/compiler/csharp/csharp_message.cc b/src/google/protobuf/compiler/csharp/csharp_message.cc index 66b87110..1defcf94 100644 --- a/src/google/protobuf/compiler/csharp/csharp_message.cc +++ b/src/google/protobuf/compiler/csharp/csharp_message.cc @@ -43,7 +43,6 @@ #include #include -#include #include #include #include @@ -106,7 +105,7 @@ std::string GetUniqueFileScopeIdentifier(const Descriptor* descriptor) { } void MessageGenerator::GenerateStaticVariables(io::Printer* printer) { - // Because descriptor.proto (Google.ProtocolBuffers.DescriptorProtos) is + // Because descriptor.proto (Google.Protobuf.DescriptorProtos) is // used in the construction of descriptors, we have a tricky bootstrapping // problem. To help control static initialization order, we make sure all // descriptors and other static data that depends on them are members of @@ -115,14 +114,12 @@ void MessageGenerator::GenerateStaticVariables(io::Printer* printer) { std::string identifier = GetUniqueFileScopeIdentifier(descriptor_); - if (!use_lite_runtime()) { - // The descriptor for this type. - printer->Print( - "internal static pbd::MessageDescriptor internal__$identifier$__Descriptor;\n" - "internal static pb::FieldAccess.FieldAccessorTable<$full_class_name$, $full_class_name$.Builder> internal__$identifier$__FieldAccessorTable;\n", - "identifier", GetUniqueFileScopeIdentifier(descriptor_), - "full_class_name", full_class_name()); - } + // The descriptor for this type. + printer->Print( + "internal static pbd::MessageDescriptor internal__$identifier$__Descriptor;\n" + "internal static pb::FieldAccess.FieldAccessorTable<$full_class_name$> internal__$identifier$__FieldAccessorTable;\n", + "identifier", GetUniqueFileScopeIdentifier(descriptor_), + "full_class_name", full_class_name()); for (int i = 0; i < descriptor_->nested_type_count(); i++) { MessageGenerator messageGenerator(descriptor_->nested_type(i)); @@ -139,139 +136,106 @@ void MessageGenerator::GenerateStaticVariableInitializers(io::Printer* printer) vars["parent"] = GetUniqueFileScopeIdentifier( descriptor_->containing_type()); } - if (!use_lite_runtime()) { - printer->Print(vars, "internal__$identifier$__Descriptor = "); + printer->Print(vars, "internal__$identifier$__Descriptor = "); - if (!descriptor_->containing_type()) { - printer->Print(vars, "Descriptor.MessageTypes[$index$];\n"); - } else { - printer->Print(vars, "internal__$parent$__Descriptor.NestedTypes[$index$];\n"); - } + if (!descriptor_->containing_type()) { + printer->Print(vars, "Descriptor.MessageTypes[$index$];\n"); + } else { + printer->Print(vars, "internal__$parent$__Descriptor.NestedTypes[$index$];\n"); + } - printer->Print( - vars, - "internal__$identifier$__FieldAccessorTable = \n" - " new pb::FieldAccess.FieldAccessorTable<$full_class_name$, $full_class_name$.Builder>(internal__$identifier$__Descriptor,\n"); - printer->Print(" new string[] { "); - for (int i = 0; i < descriptor_->field_count(); i++) { - printer->Print("\"$property_name$\", ", - "property_name", GetPropertyName(descriptor_->field(i))); - } - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - printer->Print("\"$oneof_name$\", ", - "oneof_name", - UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), true)); - } - printer->Print("});\n"); + printer->Print( + vars, + "internal__$identifier$__FieldAccessorTable = \n" + " new pb::FieldAccess.FieldAccessorTable<$full_class_name$>(internal__$identifier$__Descriptor,\n"); + printer->Print(" new string[] { "); + for (int i = 0; i < descriptor_->field_count(); i++) { + printer->Print("\"$property_name$\", ", + "property_name", GetPropertyName(descriptor_->field(i))); + } + for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { + printer->Print("\"$oneof_name$\", ", + "oneof_name", + UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), true)); } + printer->Print("});\n"); // Generate static member initializers for all nested types. for (int i = 0; i < descriptor_->nested_type_count(); i++) { MessageGenerator messageGenerator(descriptor_->nested_type(i)); messageGenerator.GenerateStaticVariableInitializers(printer); } - - for (int i = 0; i < descriptor_->extension_count(); i++) { - ExtensionGenerator extensionGenerator(descriptor_->extension(i)); - extensionGenerator.GenerateStaticVariableInitializers(printer); - } } void MessageGenerator::Generate(io::Printer* printer) { map vars; vars["class_name"] = class_name(); vars["access_level"] = class_access_level(); - vars["extendable_or_generated"] = descriptor_->extension_range_count() > 0 ? - "Extendable" : "Generated"; - vars["suffix"] = runtime_suffix(); vars["umbrella_class_name"] = GetFullUmbrellaClassName(descriptor_->file()); vars["identifier"] = GetUniqueFileScopeIdentifier(descriptor_); printer->Print( - "[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n"); + "[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n"); WriteGeneratedCodeAttributes(printer); printer->Print( vars, - "$access_level$ sealed partial class $class_name$ : pb::$extendable_or_generated$Message$suffix$<$class_name$, $class_name$.Builder> {\n"); + "$access_level$ sealed partial class $class_name$ : pb::IMessage<$class_name$> {\n"); printer->Indent(); - printer->Print( - vars, - "private $class_name$() { }\n" // Private ctor. - // Must call MakeReadOnly() to make sure all lists are made read-only - "private static readonly $class_name$ defaultInstance = new $class_name$().MakeReadOnly();\n"); - if (optimize_speed()) { - printer->Print( - "private static readonly string[] _$name$FieldNames = " - "new string[] { $slash$$field_names$$slash$ };\n", - "name", UnderscoresToCamelCase(class_name(), false), - "field_names", JoinStrings(field_names(), "\", \""), + // All static fields and properties + printer->Print( + "private static readonly string[] _fieldNames = " + "new string[] { $slash$$field_names$$slash$ };\n", + "field_names", JoinStrings(field_names(), "\", \""), "slash", field_names().size() > 0 ? "\"" : ""); - std::vector tags; - for (int i = 0; i < field_names().size(); i++) { - uint32 tag = internal::WireFormat::MakeTag( - descriptor_->FindFieldByName(field_names()[i])); - tags.push_back(SimpleItoa(tag)); - } - printer->Print( - "private static readonly uint[] _$name$FieldTags = new uint[] { $tags$ };\n", - "name", UnderscoresToCamelCase(class_name(), false), - "tags", JoinStrings(tags, ", ")); + std::vector tags; + for (int i = 0; i < field_names().size(); i++) { + uint32 tag = internal::WireFormat::MakeTag( + descriptor_->FindFieldByName(field_names()[i])); + tags.push_back(SimpleItoa(tag)); } + printer->Print( + "private static readonly uint[] _fieldTags = new uint[] { $tags$ };\n", + "tags", JoinStrings(tags, ", ")); + printer->Print( vars, - "public static $class_name$ DefaultInstance {\n" - " get { return defaultInstance; }\n" + "public static pbd::MessageDescriptor Descriptor {\n" + " get { return $umbrella_class_name$.internal__$identifier$__Descriptor; }\n" "}\n" "\n" - "public override $class_name$ DefaultInstanceForType {\n" - " get { return DefaultInstance; }\n" + "protected override pb::FieldAccess.FieldAccessorTable<$class_name$> InternalFieldAccessors {\n" + " get { return $umbrella_class_name$.internal__$identifier$__FieldAccessorTable; }\n" "}\n" - "\n" - "protected override $class_name$ ThisMessage {\n" - " get { return this; }\n" - "}\n\n"); + "\n"); - if (!use_lite_runtime()) { - printer->Print( - vars, - "public static pbd::MessageDescriptor Descriptor {\n" - " get { return $umbrella_class_name$.internal__$identifier$__Descriptor; }\n" - "}\n" - "\n" - "protected override pb::FieldAccess.FieldAccessorTable<$class_name$, $class_name$.Builder> InternalFieldAccessors {\n" - " get { return $umbrella_class_name$.internal__$identifier$__FieldAccessorTable; }\n" - "}\n" - "\n"); - } + // Constructors + printer->Print( + vars, + "public $class_name$() { }\n"); // Public parameterless ctor. - // Extensions don't need to go in an extra nested type - for (int i = 0; i < descriptor_->extension_count(); i++) { - ExtensionGenerator extensionGenerator(descriptor_->extension(i)); - extensionGenerator.Generate(printer); - } + printer->Print( + vars, + "public $class_name$($class_name$ other) {\n" + " MergeWith(other);\n" + "}\n"); // Merge ctor. - if (descriptor_->enum_type_count() + descriptor_->nested_type_count() > 0) { - printer->Print("#region Nested types\n" - "[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n"); - WriteGeneratedCodeAttributes(printer); - printer->Print("public static partial class Types {\n"); - printer->Indent(); - for (int i = 0; i < descriptor_->enum_type_count(); i++) { - EnumGenerator enumGenerator(descriptor_->enum_type(i)); - enumGenerator.Generate(printer); - } - for (int i = 0; i < descriptor_->nested_type_count(); i++) { - MessageGenerator messageGenerator(descriptor_->nested_type(i)); - messageGenerator.Generate(printer); - } - printer->Outdent(); - printer->Print("}\n" - "#endregion\n" - "\n"); + // Fields/properties + for (int i = 0; i < descriptor_->field_count(); i++) { + const FieldDescriptor* fieldDescriptor = descriptor_->field(i); + + // Rats: we lose the debug comment here :( + printer->Print( + "public const int $field_constant_name$ = $index$;\n", + "field_constant_name", GetFieldConstantName(fieldDescriptor), + "index", SimpleItoa(fieldDescriptor->number())); + scoped_ptr generator( + CreateFieldGeneratorInternal(fieldDescriptor)); + generator->GenerateMembers(printer); + printer->Print("\n"); } - // oneof + // oneof properties for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { vars["name"] = UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), false); vars["property_name"] = UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), true); @@ -280,13 +244,13 @@ void MessageGenerator::Generate(io::Printer* printer) { "private object $name$_;\n" "public enum $property_name$OneofCase {\n"); printer->Indent(); + printer->Print("None = 0,\n"); for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); printer->Print("$field_property_name$ = $index$,\n", "field_property_name", GetPropertyName(field), "index", SimpleItoa(field->number())); } - printer->Print("None = 0,\n"); printer->Outdent(); printer->Print("}\n"); printer->Print( @@ -294,243 +258,78 @@ void MessageGenerator::Generate(io::Printer* printer) { "private $property_name$OneofCase $name$Case_ = $property_name$OneofCase.None;\n" "public $property_name$OneofCase $property_name$Case {\n" " get { return $name$Case_; }\n" + "}\n\n" + "private Clear$property_name$() {;\n" + " $name$Case_ = $property_name$OneofCase.None;" + " $name$_ = null;" "}\n\n"); } - // Fields - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* fieldDescriptor = descriptor_->field(i); + // TODO(jonskeet): Map properties - // Rats: we lose the debug comment here :( - printer->Print( - "public const int $field_constant_name$ = $index$;\n", - "field_constant_name", GetFieldConstantName(fieldDescriptor), - "index", SimpleItoa(fieldDescriptor->number())); - scoped_ptr generator( - CreateFieldGeneratorInternal(fieldDescriptor)); - generator->GenerateMembers(printer); - printer->Print("\n"); - } + // Standard methods + GenerateMessageSerializationMethods(printer); + GenerateMergingMethods(printer); - if (optimize_speed()) { - if (SupportFieldPresence(descriptor_->file())) { - GenerateIsInitialized(printer); + // Nested messages and enums + if (descriptor_->enum_type_count() + descriptor_->nested_type_count() > 0) { + printer->Print("#region Nested types\n" + "[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n"); + WriteGeneratedCodeAttributes(printer); + printer->Print("public static partial class Types {\n"); + printer->Indent(); + for (int i = 0; i < descriptor_->enum_type_count(); i++) { + EnumGenerator enumGenerator(descriptor_->enum_type(i)); + enumGenerator.Generate(printer); } - GenerateMessageSerializationMethods(printer); - } - if (use_lite_runtime()) { - GenerateLiteRuntimeMethods(printer); - } - - GenerateParseFromMethods(printer); - GenerateBuilder(printer); - - // Force the static initialization code for the file to run, since it may - // initialize static variables declared in this class. - printer->Print(vars, "static $class_name$() {\n"); - // We call object.ReferenceEquals() just to make it a valid statement on its own. - // Another option would be GetType(), but that causes problems in DescriptorProtoFile, - // where the bootstrapping is somewhat recursive - type initializers call - // each other, effectively. We temporarily see Descriptor as null. - printer->Print( - vars, - " object.ReferenceEquals($umbrella_class_name$.Descriptor, null);\n" - "}\n"); - - printer->Outdent(); - printer->Print("}\n"); - printer->Print("\n"); - -} - -void MessageGenerator::GenerateLiteRuntimeMethods(io::Printer* printer) { - map vars; - vars["class_name"] = class_name(); - - bool callbase = descriptor_->extension_range_count() > 0; - printer->Print("#region Lite runtime methods\n" - "public override int GetHashCode() {\n"); - printer->Indent(); - printer->Print("int hash = GetType().GetHashCode();\n"); - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - if (field->containing_oneof() == NULL) { - scoped_ptr generator( - CreateFieldGeneratorInternal(field)); - generator->WriteHash(printer); + for (int i = 0; i < descriptor_->nested_type_count(); i++) { + MessageGenerator messageGenerator(descriptor_->nested_type(i)); + messageGenerator.Generate(printer); } - } - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - string name = UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), false); - string property_name = UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), true); - printer->Print( - "if ($name$Case_ != $property_name$OneofCase.None) {\n" - " hash ^= $name$_.GetHashCode();\n" - "}\n", - "name", UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), false), - "property_name", - UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), true)); - } - if (callbase) { - printer->Print("hash ^= base.GetHashCode();\n"); - } - printer->Print("return hash;\n"); - printer->Outdent(); - printer->Print("}\n"); - printer->Print("\n"); - - printer->Print("public override bool Equals(object obj) {\n"); - printer->Indent(); - printer->Print( - vars, - "$class_name$ other = obj as $class_name$;\n" - "if (other == null) return false;\n"); - for (int i = 0; i < descriptor_->field_count(); i++) { - scoped_ptr generator( - CreateFieldGeneratorInternal(descriptor_->field(i))); - generator->WriteEquals(printer); - } - if (callbase) { - printer->Print("if (!base.Equals(other)) return false;\n"); - } - printer->Print("return true;\n"); - printer->Outdent(); - printer->Print("}\n"); - printer->Print("\n"); - - printer->Print( - "public override void PrintTo(global::System.IO.TextWriter writer) {\n"); - printer->Indent(); - - for (int i = 0; i < fields_by_number().size(); i++) { - scoped_ptr generator( - CreateFieldGeneratorInternal(fields_by_number()[i])); - generator->WriteToString(printer); + printer->Outdent(); + printer->Print("}\n" + "#endregion\n" + "\n"); } - if (callbase) { - printer->Print("base.PrintTo(writer);\n"); - } printer->Outdent(); printer->Print("}\n"); - printer->Print("#endregion\n"); printer->Print("\n"); -} -bool CompareExtensionRangesStart(const Descriptor::ExtensionRange* r1, - const Descriptor::ExtensionRange* r2) { - return r1->start < r2->start; } void MessageGenerator::GenerateMessageSerializationMethods(io::Printer* printer) { - std::vector extension_ranges_sorted; - for (int i = 0; i < descriptor_->extension_range_count(); i++) { - extension_ranges_sorted.push_back(descriptor_->extension_range(i)); - } - std::sort(extension_ranges_sorted.begin(), extension_ranges_sorted.end(), - CompareExtensionRangesStart); - printer->Print( - "public override void WriteTo(pb::ICodedOutputStream output) {\n"); + "public void WriteTo(pb::ICodedOutputStream output) {\n"); printer->Indent(); - // Make sure we've computed the serialized length, so that packed fields are generated correctly. - printer->Print("CalcSerializedSize();\n" - "string[] field_names = _$class_name$FieldNames;\n", - "class_name", UnderscoresToCamelCase(class_name(), false)); - if (descriptor_->extension_range_count()) { - printer->Print( - "pb::ExtendableMessage$runtime_suffix$<$class_name$, $class_name$.Builder>.ExtensionWriter extensionWriter = CreateExtensionWriter(this);\n", - "class_name", class_name(), - "runtime_suffix", runtime_suffix()); - } - - // Merge the fields and the extension ranges, both sorted by field number. - for (int i = 0, j = 0; - i < fields_by_number().size() || j < extension_ranges_sorted.size();) { - if (i == fields_by_number().size()) { - GenerateSerializeOneExtensionRange(printer, extension_ranges_sorted[j++]); - } else if (j == extension_ranges_sorted.size()) { - GenerateSerializeOneField(printer, fields_by_number()[i++]); - } else if (fields_by_number()[i]->number() - < extension_ranges_sorted[j]->start) { - GenerateSerializeOneField(printer, fields_by_number()[i++]); - } else { - GenerateSerializeOneExtensionRange(printer, extension_ranges_sorted[j++]); - } - } + printer->Print("string[] fieldNames = _fieldNames;\n"); - if (!use_lite_runtime()) { - if (descriptor_->options().message_set_wire_format()) - { - printer->Print("UnknownFields.WriteAsMessageSetTo(output);\n"); - } else { - printer->Print("UnknownFields.WriteTo(output);\n"); - } + // Serialize all the fields + for (int i = 0; i < fields_by_number().size(); i++) { + scoped_ptr generator( + CreateFieldGeneratorInternal(fields_by_number()[i])); + generator->GenerateSerializationCode(printer); } + // TODO(jonskeet): Memoize size of frozen messages? printer->Outdent(); printer->Print( "}\n" "\n" - "private int memoizedSerializedSize = -1;\n" - "public override int SerializedSize {\n"); + "public int CalculateSerializedSize() {\n"); printer->Indent(); - printer->Print("get {\n"); - printer->Indent(); - printer->Print( - "int size = memoizedSerializedSize;\n" - "if (size != -1) return size;\n" - "return CalcSerializedSize();\n"); - printer->Outdent(); - printer->Print("}\n"); - printer->Outdent(); - printer->Print("}\n"); - printer->Print("\n"); - - printer->Print("private int CalcSerializedSize() {\n"); - printer->Indent(); - printer->Print( - "int size = memoizedSerializedSize;\n" - "if (size != -1) return size;\n" - "\n" - "size = 0;\n"); + printer->Print("int size = 0;\n"); for (int i = 0; i < descriptor_->field_count(); i++) { scoped_ptr generator( CreateFieldGeneratorInternal(descriptor_->field(i))); generator->GenerateSerializedSizeCode(printer); } - if (descriptor_->extension_range_count() > 0) { - printer->Print("size += ExtensionsSerializedSize;\n"); - } - - if (!use_lite_runtime()) { - if (descriptor_->options().message_set_wire_format()) { - printer->Print("size += UnknownFields.SerializedSizeAsMessageSet;\n"); - } else { - printer->Print("size += UnknownFields.SerializedSize;\n"); - } - } - printer->Print( - "memoizedSerializedSize = size;\n" - "return size;\n"); + printer->Print("return size;\n"); printer->Outdent(); printer->Print("}\n"); } -void MessageGenerator::GenerateSerializeOneField( - io::Printer* printer, const FieldDescriptor* fieldDescriptor) { - scoped_ptr generator( - CreateFieldGeneratorInternal(fieldDescriptor)); - generator->GenerateSerializationCode(printer); -} - -void MessageGenerator::GenerateSerializeOneExtensionRange( - io::Printer* printer, const Descriptor::ExtensionRange* extensionRange) { - printer->Print("extensionWriter.WriteUntil($range_end$, output);\n", - "range_end", SimpleItoa(extensionRange->end)); -} - -void MessageGenerator::GenerateParseFromMethods(io::Printer* printer) { +void MessageGenerator::GenerateMergingMethods(io::Printer* printer) { // Note: These are separate from GenerateMessageSerializationMethods() // because they need to be generated even for messages that are optimized // for code size. @@ -539,339 +338,72 @@ void MessageGenerator::GenerateParseFromMethods(io::Printer* printer) { printer->Print( vars, - "public static $class_name$ ParseFrom(pb::ByteString data) {\n" - " return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();\n" - "}\n" - "public static $class_name$ ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) {\n" - " return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();\n" - "}\n" - "public static $class_name$ ParseFrom(byte[] data) {\n" - " return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed();\n" - "}\n" - "public static $class_name$ ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) {\n" - " return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed();\n" - "}\n" - "public static $class_name$ ParseFrom(global::System.IO.Stream input) {\n" - " return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();\n" - "}\n" - "public static $class_name$ ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {\n" - " return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();\n" - "}\n" - "public static $class_name$ ParseDelimitedFrom(global::System.IO.Stream input) {\n" - " return CreateBuilder().MergeDelimitedFrom(input).BuildParsed();\n" - "}\n" - "public static $class_name$ ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) {\n" - " return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed();\n" - "}\n" - "public static $class_name$ ParseFrom(pb::ICodedInputStream input) {\n" - " return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed();\n" - "}\n" - "public static $class_name$ ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {\n" - " return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed();\n" - "}\n"); -} - -void MessageGenerator::GenerateBuilder(io::Printer* printer) { - map vars; - vars["class_name"] = class_name(); - vars["access_level"] = class_access_level(); - vars["extendable_or_generated"] = descriptor_->extension_range_count() > 0 ? - "Extendable" : "Generated"; - vars["suffix"] = runtime_suffix(); - - printer->Print(vars, "private $class_name$ MakeReadOnly() {\n"); - printer->Indent(); - for (int i = 0; i < descriptor_->field_count(); i++) { - scoped_ptr generator( - CreateFieldGeneratorInternal(descriptor_->field(i))); - generator->GenerateBuildingCode(printer); - } - printer->Print("return this;\n"); - printer->Outdent(); - printer->Print("}\n\n"); - - printer->Print( - vars, - "public static Builder CreateBuilder() { return new Builder(); }\n" - "public override Builder ToBuilder() { return CreateBuilder(this); }\n" - "public override Builder CreateBuilderForType() { return new Builder(); }\n" - "public static Builder CreateBuilder($class_name$ prototype) {\n" - " return new Builder(prototype);\n" - "}\n" - "\n" - "[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]\n"); - WriteGeneratedCodeAttributes(printer); - printer->Print( - vars, - "$access_level$ sealed partial class Builder : pb::$extendable_or_generated$Builder$suffix$<$class_name$, Builder> {\n"); + "public void MergeWith($class_name$ other) {\n"); printer->Indent(); printer->Print( - "protected override Builder ThisBuilder {\n" - " get { return this; }\n" + "if (other == null) {\n" + " return;\n" "}\n"); - GenerateCommonBuilderMethods(printer); - if (optimize_speed()) { - GenerateBuilderParsingMethods(printer); - } + // TODO(jonskeet): Maps? + // Merge non-oneof fields for (int i = 0; i < descriptor_->field_count(); i++) { - scoped_ptr generator( - CreateFieldGeneratorInternal(descriptor_->field(i))); - printer->Print("\n"); - // No field comment :( - generator->GenerateBuilderMembers(printer); - } - - // oneof - for (int i = 0; i < descriptor_->oneof_decl_count(); i++) { - printer->Print("\n"); - string name = UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), false); - string property_name = UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), true); - printer->Print( - "public $property_name$OneofCase $property_name$Case {\n" - " get { return result.$name$Case_; }\n" - "}\n" - "public Builder Clear$property_name$() {\n" - " PrepareBuilder();\n" - " result.$name$_ = null;\n" - " result.$name$Case_ = $property_name$OneofCase.None;\n" - " return this;\n" - "}\n", - "name", UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), false), - "property_name", - UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), true)); - } - - printer->Outdent(); - printer->Print("}\n"); -} - -void MessageGenerator::GenerateCommonBuilderMethods(io::Printer* printer) { - map vars; - vars["class_name"] = class_name(); - vars["full_class_name"] = full_class_name(); - vars["suffix"] = runtime_suffix(); - - printer->Print( - vars, - //default constructor - "public Builder() {\n" - //Durring static initialization of message, DefaultInstance is expected to return null. - " result = DefaultInstance;\n" - " resultIsReadOnly = true;\n" - "}\n" - //clone constructor - "internal Builder($class_name$ cloneFrom) {\n" - " result = cloneFrom;\n" - " resultIsReadOnly = true;\n" - "}\n" - "\n" - "private bool resultIsReadOnly;\n" - "private $class_name$ result;\n" - "\n" - "private $class_name$ PrepareBuilder() {\n" - " if (resultIsReadOnly) {\n" - " $class_name$ original = result;\n" - " result = new $class_name$();\n" - " resultIsReadOnly = false;\n" - " MergeFrom(original);\n" - " }\n" - " return result;\n" - "}\n" - "\n" - "public override bool IsInitialized {\n" - " get { return result.IsInitialized; }\n" - "}\n" - "\n" - "protected override $class_name$ MessageBeingBuilt {\n" - " get { return PrepareBuilder(); }\n" - "}\n" - "\n"); - //Not actually expecting that DefaultInstance would ever be null here; however, we will ensure it does not break - printer->Print( - "public override Builder Clear() {\n" - " result = DefaultInstance;\n" - " resultIsReadOnly = true;\n" - " return this;\n" - "}\n" - "\n" - "public override Builder Clone() {\n" - " if (resultIsReadOnly) {\n" - " return new Builder(result);\n" - " } else {\n" - " return new Builder().MergeFrom(result);\n" - " }\n" - "}\n" - "\n"); - if (!use_lite_runtime()) { - printer->Print( - vars, - "public override pbd::MessageDescriptor DescriptorForType {\n" - " get { return $full_class_name$.Descriptor; }\n" - "}\n\n"); + if (!descriptor_->field(i)->containing_oneof()) { + scoped_ptr generator( + CreateFieldGeneratorInternal(descriptor_->field(i))); + generator->GenerateMergingCode(printer); + } } - printer->Print( - vars, - "public override $class_name$ DefaultInstanceForType {\n" - " get { return $full_class_name$.DefaultInstance; }\n" - "}\n\n"); - - printer->Print( - vars, - "public override $class_name$ BuildPartial() {\n" - " if (resultIsReadOnly) {\n" - " return result;\n" - " }\n" - " resultIsReadOnly = true;\n" - " return result.MakeReadOnly();\n" - "}\n\n"); - - if (optimize_speed()) { - printer->Print( - vars, - "public override Builder MergeFrom(pb::IMessage$suffix$ other) {\n" - " if (other is $class_name$) {\n" - " return MergeFrom(($class_name$) other);\n" - " } else {\n" - " base.MergeFrom(other);\n" - " return this;\n" - " }\n" - "}\n\n"); - - printer->Print(vars,"public override Builder MergeFrom($class_name$ other) {\n"); - // Optimization: If other is the default instance, we know none of its - // fields are set so we can skip the merge. + // Merge oneof fields + for (int i = 0; i < descriptor_->oneof_decl_count(); ++i) { + vars["name"] = UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), false); + vars["property_name"] = UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), true); + printer->Print(vars, "switch (other.$property_name$Case) {\n"); printer->Indent(); - printer->Print( - vars, - "if (other == $full_class_name$.DefaultInstance) return this;\n" - "PrepareBuilder();\n"); - for (int i = 0; i < descriptor_->field_count(); i++) { - if (!descriptor_->field(i)->containing_oneof()) { - scoped_ptr generator( - CreateFieldGeneratorInternal(descriptor_->field(i))); - generator->GenerateMergingCode(printer); - } - } - - // Merge oneof fields - for (int i = 0; i < descriptor_->oneof_decl_count(); ++i) { - vars["name"] = UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), false); - vars["property_name"] = UnderscoresToCamelCase(descriptor_->oneof_decl(i)->name(), true); - printer->Print(vars, "switch (other.$property_name$Case) {\n"); - printer->Indent(); - for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { - const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); - vars["field_property_name"] = GetPropertyName(field); - printer->Print( - vars, - "case $property_name$OneofCase.$field_property_name$: {\n"); - if (field->type() == FieldDescriptor::TYPE_GROUP || - field->type() == FieldDescriptor::TYPE_MESSAGE) { - printer->Print( - vars, - " Merge$field_property_name$(other.$field_property_name$);\n"); - } else { - printer->Print( - vars, - " Set$field_property_name$(other.$field_property_name$);\n"); - } - printer->Print(" break;\n"); - printer->Print("}\n"); - } - printer->Print(vars, "case $property_name$OneofCase.None: { break; }\n"); - printer->Outdent(); - printer->Print("}\n"); - } - - // if message type has extensions - if (descriptor_->extension_range_count() > 0) { - printer->Print(" this.MergeExtensionFields(other);\n"); - } - if (!use_lite_runtime()) { - printer->Print("this.MergeUnknownFields(other.UnknownFields);\n"); + for (int j = 0; j < descriptor_->oneof_decl(i)->field_count(); j++) { + const FieldDescriptor* field = descriptor_->oneof_decl(i)->field(j); + vars["field_property_name"] = GetPropertyName(field); + printer->Print( + vars, + "case $property_name$OneofCase.$field_property_name$:\n" + " $field_property_name$ = other.$field_property_name$;\n" + " break;\n"); } - printer->Print("return this;\n"); printer->Outdent(); printer->Print("}\n\n"); } - -} - -void MessageGenerator::GenerateBuilderParsingMethods(io::Printer* printer) { - printer->Print( - "public override Builder MergeFrom(pb::ICodedInputStream input) {\n" - " return MergeFrom(input, pb::ExtensionRegistry.Empty);\n" - "}\n\n"); - - printer->Print( - "public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {\n"); + printer->Outdent(); + printer->Print("}\n\n"); + printer->Print("public void MergeFrom(pb::ICodedInputStream input) {\n"); printer->Indent(); - printer->Print("PrepareBuilder();\n"); - if (!use_lite_runtime()) { - printer->Print("pb::UnknownFieldSet.Builder unknownFields = null;\n"); - } printer->Print( "uint tag;\n" - "string field_name;\n" - "while (input.ReadTag(out tag, out field_name)) {\n"); + "string fieldName;\n" + "while (input.ReadTag(out tag, out fieldName)) {\n" + " if (tag == 0 && fieldName != null) {"); printer->Indent(); - printer->Print("if(tag == 0 && field_name != null) {\n"); printer->Indent(); - //if you change from StringComparer.Ordinal, the array sort in FieldNames { get; } must also change - printer->Print( - "int field_ordinal = global::System.Array.BinarySearch(_$camel_class_name$FieldNames, field_name, global::System.StringComparer.Ordinal);\n" - "if(field_ordinal >= 0)\n" - " tag = _$camel_class_name$FieldTags[field_ordinal];\n" - "else {\n", - "camel_class_name", UnderscoresToCamelCase(class_name(), false)); - if (!use_lite_runtime()) { - printer->Print( - " if (unknownFields == null) {\n" // First unknown field - create builder now - " unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);\n" - " }\n"); - } printer->Print( - " ParseUnknownField(input, $prefix$extensionRegistry, tag, field_name);\n", - "prefix", use_lite_runtime() ? "" : "unknownFields, "); - printer->Print(" continue;\n"); - printer->Print("}\n"); - printer->Outdent(); - printer->Print("}\n"); - - printer->Print("switch (tag) {\n"); + "int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.String.String.Ordinal);\n" + "if (fieldOrdinal >= 0) {\n" + " tag = _fieldTags[fieldOrdinal];\n" + "}\n" + "switch(tag) {\n"); printer->Indent(); printer->Print( "case 0: {\n" // 0 signals EOF / limit reached " throw pb::InvalidProtocolBufferException.InvalidTag();\n" "}\n" - "default: {\n" - " if (pb::WireFormat.IsEndGroupTag(tag)) {\n"); - if (!use_lite_runtime()) { - printer->Print( - " if (unknownFields != null) {\n" - " this.UnknownFields = unknownFields.Build();\n" - " }\n"); - } - printer->Print( - " return this;\n" // it's an endgroup tag - " }\n"); - if (!use_lite_runtime()) { - printer->Print( - " if (unknownFields == null) {\n" // First unknown field - create builder now - " unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);\n" - " }\n"); - } - printer->Print( - " ParseUnknownField(input, $prefix$extensionRegistry, tag, field_name);\n", - "prefix", use_lite_runtime() ? "" : "unknownFields, "); - printer->Print(" break;\n"); - printer->Print("}\n"); - + "default:\n" + " if (pb::WireFormat.IsEndGroupTag(tag)) {\n" + " return;\n" + " }\n" + " break;"); // Note: we're ignoring unknown fields here. for (int i = 0; i < fields_by_number().size(); i++) { const FieldDescriptor* field = fields_by_number()[i]; internal::WireFormatLite::WireType wt = internal::WireFormat::WireTypeForFieldType(field->type()); uint32 tag = internal::WireFormatLite::MakeTag(field->number(), wt); + // TODO(jonskeet): Understand what this is trying to do if (field->is_repeated() && (wt == internal::WireFormatLite::WIRETYPE_VARINT || wt == internal::WireFormatLite::WIRETYPE_FIXED32 @@ -894,95 +426,14 @@ void MessageGenerator::GenerateBuilderParsingMethods(io::Printer* printer) { printer->Outdent(); printer->Print("}\n"); } - - printer->Outdent(); - printer->Print("}\n"); printer->Outdent(); - printer->Print("}\n"); - printer->Print("\n"); - if (!use_lite_runtime()) { - printer->Print( - "if (unknownFields != null) {\n" - " this.UnknownFields = unknownFields.Build();\n" - "}\n"); - } - printer->Print("return this;\n"); + printer->Print("}\n"); // switch printer->Outdent(); - printer->Print("}\n\n"); -} - -void MessageGenerator::GenerateIsInitialized(io::Printer* printer) { - printer->Print("public override bool IsInitialized {\n"); - printer->Indent(); - printer->Print("get {\n"); - printer->Indent(); - - // Check that all required fields in this message are set. - // TODO(kenton): We can optimize this when we switch to putting all the - // "has" fields into a single bitfield. - for (int i = 0; i < descriptor_->field_count(); i++) { - if (descriptor_->field(i)->is_required()) { - printer->Print("if (!has$property_name$) return false;\n", - "property_name", GetPropertyName(descriptor_->field(i))); - } - } - - // Now check that all embedded messages are initialized. - for (int i = 0; i < descriptor_->field_count(); i++) { - const FieldDescriptor* field = descriptor_->field(i); - - if (field->type() != FieldDescriptor::TYPE_MESSAGE || - !HasRequiredFields(field->message_type())) - { - continue; - } - // TODO(jtattermusch): shouldn't we use GetPropertyName here? - string propertyName = UnderscoresToPascalCase(GetFieldName(field)); - if (field->is_repeated()) - { - printer->Print( - "foreach ($class_name$ element in $property_name$List) {\n" - " if (!element.IsInitialized) return false;\n" - "}\n", - "class_name", GetClassName(field->message_type()), - "property_name", propertyName); - } - else if (field->is_optional()) - { - printer->Print( - "if (Has$property_name$) {\n" - " if (!$property_name$.IsInitialized) return false;\n" - "}\n", - "property_name", propertyName); - } - else - { - printer->Print( - "if (!$property_name$.IsInitialized) return false;\n", - "property_name", propertyName); - } - } - - if (descriptor_->extension_range_count() > 0) { - printer->Print("if (!ExtensionsAreInitialized) return false;\n"); - } - printer->Print("return true;\n"); + printer->Print("}\n"); // if printer->Outdent(); - printer->Print("}\n"); + printer->Print("}\n"); // while printer->Outdent(); - printer->Print("}\n"); - printer->Print("\n"); -} - -void MessageGenerator::GenerateExtensionRegistrationCode(io::Printer* printer) { - for (int i = 0; i < descriptor_->extension_count(); i++) { - ExtensionGenerator extensionGenerator(descriptor_->extension(i)); - extensionGenerator.GenerateExtensionRegistrationCode(printer); - } - for (int i = 0; i < descriptor_->nested_type_count(); i++) { - MessageGenerator messageGenerator(descriptor_->nested_type(i)); - messageGenerator.GenerateExtensionRegistrationCode(printer); - } + printer->Print("}\n\n"); // method } int MessageGenerator::GetFieldOrdinal(const FieldDescriptor* descriptor) { diff --git a/src/google/protobuf/compiler/csharp/csharp_message.h b/src/google/protobuf/compiler/csharp/csharp_message.h index ebe58618..f5f41c73 100644 --- a/src/google/protobuf/compiler/csharp/csharp_message.h +++ b/src/google/protobuf/compiler/csharp/csharp_message.h @@ -43,7 +43,6 @@ namespace protobuf { namespace compiler { namespace csharp { -class Writer; class FieldGeneratorBase; class MessageGenerator : public SourceGeneratorBase { @@ -53,7 +52,6 @@ class MessageGenerator : public SourceGeneratorBase { void GenerateStaticVariables(io::Printer* printer); void GenerateStaticVariableInitializers(io::Printer* printer); - void GenerateExtensionRegistrationCode(io::Printer* printer); void Generate(io::Printer* printer); private: @@ -61,17 +59,8 @@ class MessageGenerator : public SourceGeneratorBase { std::vector field_names_; std::vector fields_by_number_; - void GenerateLiteRuntimeMethods(io::Printer* printer); void GenerateMessageSerializationMethods(io::Printer* printer); - void GenerateSerializeOneField(io::Printer* printer, - const FieldDescriptor* fieldDescriptor); - void GenerateSerializeOneExtensionRange( - io::Printer* printer, const Descriptor::ExtensionRange* extendsionRange); - void GenerateParseFromMethods(io::Printer* printer); - void GenerateBuilder(io::Printer* printer); - void GenerateCommonBuilderMethods(io::Printer* printer); - void GenerateBuilderParsingMethods(io::Printer* printer); - void GenerateIsInitialized(io::Printer* printer); + void GenerateMergingMethods(io::Printer* printer); int GetFieldOrdinal(const FieldDescriptor* descriptor); FieldGeneratorBase* CreateFieldGeneratorInternal( @@ -95,4 +84,3 @@ class MessageGenerator : public SourceGeneratorBase { } // namespace google #endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_MESSAGE_H__ - diff --git a/src/google/protobuf/compiler/csharp/csharp_message_field.cc b/src/google/protobuf/compiler/csharp/csharp_message_field.cc index 50eb9df6..90aa201b 100644 --- a/src/google/protobuf/compiler/csharp/csharp_message_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_message_field.cc @@ -49,8 +49,8 @@ namespace csharp { MessageFieldGenerator::MessageFieldGenerator(const FieldDescriptor* descriptor, int fieldOrdinal) : FieldGeneratorBase(descriptor, fieldOrdinal) { - variables_["has_property_check"] = "has" + property_name(); - variables_["message_or_group"] = message_or_group(); + variables_["has_property_check"] = property_name() + "_ != null"; + variables_["has_not_property_check"] = property_name() + "_ == null"; } MessageFieldGenerator::~MessageFieldGenerator() { @@ -60,125 +60,42 @@ MessageFieldGenerator::~MessageFieldGenerator() { void MessageFieldGenerator::GenerateMembers(io::Printer* printer) { printer->Print( variables_, - "private bool has$property_name$;\n" "private $type_name$ $name$_;\n"); AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public bool Has$property_name$ {\n" - " get { return has$property_name$; }\n" - "}\n"); - AddDeprecatedFlag(printer); printer->Print( variables_, "public $type_name$ $property_name$ {\n" - " get { return $name$_ ?? $default_value$; }\n" - "}\n"); -} - -void MessageFieldGenerator::GenerateBuilderMembers(io::Printer* printer) { - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public bool Has$property_name$ {\n" - " get { return result.has$property_name$; }\n" - "}\n"); - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public $type_name$ $property_name$ {\n" - " get { return result.$property_name$; }\n" - " set { Set$property_name$(value); }\n" - "}\n"); - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public Builder Set$property_name$($type_name$ value) {\n"); - AddNullCheck(printer); - printer->Print( - variables_, - " PrepareBuilder();\n" - " result.has$property_name$ = true;\n" - " result.$name$_ = value;\n" - " return this;\n" - "}\n"); - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public Builder Set$property_name$($type_name$.Builder builderForValue) {\n"); - AddNullCheck(printer, "builderForValue"); - printer->Print( - variables_, - " PrepareBuilder();\n" - " result.has$property_name$ = true;\n" - " result.$name$_ = builderForValue.Build();\n" - " return this;\n" - "}\n"); - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public Builder Merge$property_name$($type_name$ value) {\n"); - AddNullCheck(printer); - printer->Print( - variables_, - " PrepareBuilder();\n" - " if (result.has$property_name$ &&\n" - " result.$name$_ != $default_value$) {\n" - " result.$name$_ = $type_name$.CreateBuilder(result.$name$_).MergeFrom(value).BuildPartial();\n" - " } else {\n" - " result.$name$_ = value;\n" - " }\n" - " result.has$property_name$ = true;\n" - " return this;\n" - "}\n"); - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public Builder Clear$property_name$() {\n" - " PrepareBuilder();\n" - " result.has$property_name$ = false;\n" - " result.$name$_ = null;\n" - " return this;\n" + " get { return $name$_; }\n" + " set { return $name$_ = value; }\n" "}\n"); } void MessageFieldGenerator::GenerateMergingCode(io::Printer* printer) { printer->Print( variables_, - "if (other.Has$property_name$) {\n" - " Merge$property_name$(other.$property_name$);\n" + "if (other.$has_property_check$) {\n" + " if ($has_not_property_check) {\n" + " $name$_ = new $type_name$();\n" + " }\n" + " $property_name$.MergeWith(other.$property_name);\n" "}\n"); } -void MessageFieldGenerator::GenerateBuildingCode(io::Printer* printer) { - // Nothing to do for singular fields -} - void MessageFieldGenerator::GenerateParsingCode(io::Printer* printer) { printer->Print( variables_, - "$type_name$.Builder subBuilder = $type_name$.CreateBuilder();\n" - "if (result.has$property_name$) {\n" - " subBuilder.MergeFrom($property_name$);\n" - "}\n"); - - if (descriptor_->type() == FieldDescriptor::TYPE_GROUP) { - printer->Print( - variables_, - "input.ReadGroup($number$, subBuilder, extensionRegistry);\n"); - } else { - printer->Print("input.ReadMessage(subBuilder, extensionRegistry);\n"); - } - printer->Print( - variables_, - "$property_name$ = subBuilder.BuildPartial();\n"); + "if ($has_not_property_check) {\n" + " $name$_ = new $type_name$();\n" + "}\n" + "input.ReadMessage($name$_);\n"); // No need to support TYPE_GROUP... } void MessageFieldGenerator::GenerateSerializationCode(io::Printer* printer) { + // TODO(jonskeet): Why are we using array access instead of a literal here? printer->Print( variables_, "if ($has_property_check$) {\n" - " output.Write$message_or_group$($number$, field_names[$field_ordinal$], $property_name$);\n" + " output.WriteMessage($number$, fieldNames[$field_ordinal$], $property_name$);\n" "}\n"); } @@ -186,19 +103,19 @@ void MessageFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { printer->Print( variables_, "if ($has_property_check$) {\n" - " size += pb::CodedOutputStream.Compute$message_or_group$Size($number$, $property_name$);\n" + " size += pb::CodedOutputStream.ComputeMessageSize($number$, $property_name$);\n" "}\n"); } void MessageFieldGenerator::WriteHash(io::Printer* printer) { printer->Print( variables_, - "if (has$property_name$) hash ^= $name$_.GetHashCode();\n"); + "if ($has_property_check$) hash ^= $name$_.GetHashCode();\n"); } void MessageFieldGenerator::WriteEquals(io::Printer* printer) { printer->Print( variables_, - "if (has$property_name$ != other.has$property_name$ || (has$property_name$ && !$name$_.Equals(other.$name$_))) return false;\n"); + "if (!object.Equals($property_name$_, other.$property_name$_)) return false;\n"); } void MessageFieldGenerator::WriteToString(io::Printer* printer) { variables_["field_name"] = GetFieldName(descriptor_); @@ -218,118 +135,30 @@ MessageOneofFieldGenerator::~MessageOneofFieldGenerator() { } void MessageOneofFieldGenerator::GenerateMembers(io::Printer* printer) { - if (SupportFieldPresence(descriptor_->file())) { - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public bool Has$property_name$ {\n" - " get { return $has_property_check$; }\n" - "}\n"); - } AddDeprecatedFlag(printer); printer->Print( variables_, "public $type_name$ $property_name$ {\n" - " get { return $has_property_check$ ? ($type_name$) $oneof_name$_ : $default_value$; }\n" - "}\n"); -} - -void MessageOneofFieldGenerator::GenerateBuilderMembers(io::Printer* printer) { - if (SupportFieldPresence(descriptor_->file())) { - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public bool Has$property_name$ {\n" - " get { return result.$has_property_check$; }\n" - "}\n"); - } - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public $type_name$ $property_name$ {\n" - " get { return result.$has_property_check$ ? ($type_name$) result.$oneof_name$_ : $default_value$; }\n" - " set { Set$property_name$(value); }\n" - "}\n"); - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public Builder Set$property_name$($type_name$ value) {\n"); - AddNullCheck(printer); - printer->Print( - variables_, - " PrepareBuilder();\n" - " result.$oneof_name$Case_ = $oneof_property_name$OneofCase.$property_name$;\n" - " result.$oneof_name$_ = value;\n" - " return this;\n" - "}\n"); - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public Builder Set$property_name$($type_name$.Builder builderForValue) {\n"); - AddNullCheck(printer, "builderForValue"); - printer->Print( - variables_, - " PrepareBuilder();\n" - " result.$oneof_name$Case_ = $oneof_property_name$OneofCase.$property_name$;\n" - " result.$oneof_name$_ = builderForValue.Build();\n" - " return this;\n" - "}\n"); - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public Builder Merge$property_name$($type_name$ value) {\n"); - AddNullCheck(printer); - printer->Print( - variables_, - " PrepareBuilder();\n" - " if (result.$has_property_check$ &&\n" - " result.$property_name$ != $default_value$) {\n" - " result.$oneof_name$_ = $type_name$.CreateBuilder(result.$property_name$).MergeFrom(value).BuildPartial();\n" - " } else {\n" - " result.$oneof_name$_ = value;\n" - " }\n" - " result.$oneof_name$Case_ = $oneof_property_name$OneofCase.$property_name$;\n" - " return this;\n" - "}\n"); - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public Builder Clear$property_name$() {\n" - " if (result.$has_property_check$) {\n" - " PrepareBuilder();\n" - " result.$oneof_name$Case_ = $oneof_property_name$OneofCase.None;\n" - " result.$oneof_name$_ = null;\n" - " }\n" - " return this;\n" + " get { return $has_property_check$ ? ($type_name$) $oneof_name$_ : null; }\n" + " set { \n" + " $name$_ = value;" + " $oneof_name$Case_ = value == null ? $oneof_property_name$Case.None : $oneof_property_name$Case.$property_name$; }\n" + " } \n" "}\n"); } void MessageOneofFieldGenerator::GenerateParsingCode(io::Printer* printer) { + // TODO(jonskeet): We may be able to do better than this printer->Print( variables_, - "$type_name$.Builder subBuilder = $type_name$.CreateBuilder();\n" - "if (result.$has_property_check$) {\n" - " subBuilder.MergeFrom($property_name$);\n" - "}\n"); - - if (descriptor_->type() == FieldDescriptor::TYPE_GROUP) { - printer->Print( - variables_, - "input.ReadGroup($number$, subBuilder, extensionRegistry);\n"); - } else { - printer->Print("input.ReadMessage(subBuilder, extensionRegistry);\n"); - } - printer->Print( - variables_, - "result.$oneof_name$_ = subBuilder.BuildPartial();\n" - "result.$oneof_name$Case_ = $oneof_property_name$OneofCase.$property_name$;\n"); + "$type_name$ subBuilder = new type_name$();\n" + "if ($has_property_check$) {\n" + " subBuilder.MergeWith($property_name$);\n" + "}\n" + "input.ReadMessage(subBuilder);\n" // No support of TYPE_GROUP + "$oneof_property_name$ = subBuilder;\n"); } -void MessageOneofFieldGenerator::WriteEquals(io::Printer* printer) { - printer->Print( - variables_, - "if (!$property_name$.Equals(other.$property_name$)) return false;\n"); -} void MessageOneofFieldGenerator::WriteToString(io::Printer* printer) { printer->Print( variables_, diff --git a/src/google/protobuf/compiler/csharp/csharp_message_field.h b/src/google/protobuf/compiler/csharp/csharp_message_field.h index d820908c..02053b4f 100644 --- a/src/google/protobuf/compiler/csharp/csharp_message_field.h +++ b/src/google/protobuf/compiler/csharp/csharp_message_field.h @@ -41,17 +41,13 @@ namespace protobuf { namespace compiler { namespace csharp { -class Writer; - class MessageFieldGenerator : public FieldGeneratorBase { public: MessageFieldGenerator(const FieldDescriptor* descriptor, int fieldOrdinal); ~MessageFieldGenerator(); virtual void GenerateMembers(io::Printer* printer); - virtual void GenerateBuilderMembers(io::Printer* printer); virtual void GenerateMergingCode(io::Printer* printer); - virtual void GenerateBuildingCode(io::Printer* printer); virtual void GenerateParsingCode(io::Printer* printer); virtual void GenerateSerializationCode(io::Printer* printer); virtual void GenerateSerializedSizeCode(io::Printer* printer); @@ -70,8 +66,6 @@ class MessageOneofFieldGenerator : public MessageFieldGenerator { ~MessageOneofFieldGenerator(); virtual void GenerateMembers(io::Printer* printer); - virtual void GenerateBuilderMembers(io::Printer* printer); - virtual void WriteEquals(io::Printer* printer); virtual void WriteToString(io::Printer* printer); virtual void GenerateParsingCode(io::Printer* printer); diff --git a/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc b/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc index 652eb6b9..bc4858fc 100644 --- a/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc @@ -49,82 +49,37 @@ namespace csharp { PrimitiveFieldGenerator::PrimitiveFieldGenerator( const FieldDescriptor* descriptor, int fieldOrdinal) : FieldGeneratorBase(descriptor, fieldOrdinal) { + // TODO(jonskeet): Make this cleaner... + is_value_type = descriptor->type() != FieldDescriptor::TYPE_STRING + && descriptor->type() != FieldDescriptor::TYPE_BYTES; } PrimitiveFieldGenerator::~PrimitiveFieldGenerator() { - } void PrimitiveFieldGenerator::GenerateMembers(io::Printer* printer) { - if (SupportFieldPresence(descriptor_->file())) { - printer->Print(variables_, "private bool has$property_name$;\n"); - } + // TODO(jonskeet): Work out whether we want to prevent the fields from ever being + // null, or whether we just handle it, in the cases of bytes and string. + // (Basically, should null-handling code be in the getter or the setter?) printer->Print( variables_, "private $type_name$ $name_def_message$;\n"); AddDeprecatedFlag(printer); - if (SupportFieldPresence(descriptor_->file())) { - printer->Print( - variables_, - "public bool Has$property_name$ {\n" - " get { return has$property_name$; }\n" - "}\n"); - } - AddPublicMemberAttributes(printer); printer->Print( variables_, "public $type_name$ $property_name$ {\n" - " get { return $name$_; }\n" - "}\n"); -} - -void PrimitiveFieldGenerator::GenerateBuilderMembers(io::Printer* printer) { - AddDeprecatedFlag(printer); - if (SupportFieldPresence(descriptor_->file())) { - printer->Print( - variables_, - "public bool Has$property_name$ {\n" - " get { return result.has$property_name$; }\n" - "}\n"); - } - AddPublicMemberAttributes(printer); - printer->Print( - variables_, - "public $type_name$ $property_name$ {\n" - " get { return result.$property_name$; }\n" - " set { Set$property_name$(value); }\n" - "}\n"); - AddPublicMemberAttributes(printer); - printer->Print( - variables_, - "public Builder Set$property_name$($type_name$ value) {\n"); - AddNullCheck(printer); - printer->Print(" PrepareBuilder();\n"); - if (SupportFieldPresence(descriptor_->file())) { + " get { return $name$_; }\n"); + if (is_value_type) { printer->Print( variables_, - " result.has$property_name$ = true;\n"); - } - printer->Print( - variables_, - " result.$name$_ = value;\n" - " return this;\n" - "}\n"); - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public Builder Clear$property_name$() {\n" - " PrepareBuilder();\n"); - if (SupportFieldPresence(descriptor_->file())) { + " set { $name$_ = value; }\n"); + + } else { printer->Print( variables_, - " result.has$property_name$ = false;\n"); + " set { $name$_ = value ?? $default_value$; }\n"); } - printer->Print( - variables_, - " result.$name$_ = $default_value$;\n" - " return this;\n" - "}\n"); + printer->Print("}\n\n"); } void PrimitiveFieldGenerator::GenerateMergingCode(io::Printer* printer) { @@ -135,27 +90,17 @@ void PrimitiveFieldGenerator::GenerateMergingCode(io::Printer* printer) { "}\n"); } -void PrimitiveFieldGenerator::GenerateBuildingCode(io::Printer* printer) { - // Nothing to do here for primitive types -} - void PrimitiveFieldGenerator::GenerateParsingCode(io::Printer* printer) { - if (SupportFieldPresence(descriptor_->file())) { - printer->Print( - variables_, - "result.has$property_name$ = input.Read$capitalized_type_name$(ref result.$name$_);\n"); - } else { - printer->Print( - variables_, - "input.Read$capitalized_type_name$(ref result.$name$_);\n"); - } + printer->Print( + variables_, + "input.Read$capitalized_type_name$(ref result.$name$_);\n"); } void PrimitiveFieldGenerator::GenerateSerializationCode(io::Printer* printer) { printer->Print( variables_, "if ($has_property_check$) {\n" - " output.Write$capitalized_type_name$($number$, field_names[$field_ordinal$], $property_name$);\n" + " output.Write$capitalized_type_name$($number$, fieldNames[$field_ordinal$], $property_name$);\n" "}\n"); } @@ -171,24 +116,18 @@ void PrimitiveFieldGenerator::WriteHash(io::Printer* printer) { printer->Print( variables_, "if ($has_property_check$) {\n" - " hash ^= $name$_.GetHashCode();\n" + " hash ^= $property_name$.GetHashCode();\n" "}\n"); } void PrimitiveFieldGenerator::WriteEquals(io::Printer* printer) { - if (SupportFieldPresence(descriptor_->file())) { - printer->Print( - variables_, - "if (has$property_name$ != other.has$property_name$ || (has$property_name$ && !$name$_.Equals(other.$name$_))) return false;\n"); - } else { - printer->Print( - variables_, - "if (!$name$_.Equals(other.$name$_)) return false;\n"); - } + printer->Print( + variables_, + "if ($property_name$ != other.$property_name$) return false;\n"); } void PrimitiveFieldGenerator::WriteToString(io::Printer* printer) { printer->Print( variables_, - "PrintField(\"$descriptor_name$\", $has_property_check$, $name$_, writer);\n"); + "PrintField(\"$descriptor_name$\", $has_property_check$, $property_name$, writer);\n"); } PrimitiveOneofFieldGenerator::PrimitiveOneofFieldGenerator( @@ -201,79 +140,43 @@ PrimitiveOneofFieldGenerator::~PrimitiveOneofFieldGenerator() { } void PrimitiveOneofFieldGenerator::GenerateMembers(io::Printer* printer) { + // TODO(jonskeet): What should foo.OneofIntField = 0; do? Clear the oneof? + // Currently foo.OneOfStringField = null will clear the oneof, but foo.OneOfStringField = "" won't. Ick. AddDeprecatedFlag(printer); - if (SupportFieldPresence(descriptor_->file())) { - printer->Print( - variables_, - "public bool Has$property_name$ {\n" - " get { return $has_property_check$; }\n" - "}\n"); - } - AddPublicMemberAttributes(printer); printer->Print( variables_, "public $type_name$ $property_name$ {\n" " get { return $has_property_check$ ? ($type_name$) $oneof_name$_ : $default_value$; }\n" - "}\n"); -} - -void PrimitiveOneofFieldGenerator::GenerateBuilderMembers(io::Printer* printer) { - AddDeprecatedFlag(printer); - if (SupportFieldPresence(descriptor_->file())) { + " set {"); + if (is_value_type) { + printer->Print( + variables_, + " $oneof_name$_ = value;\n" + " $oneof_name$Case_ = $oneof_property_name$Case.$property_name$;\n"); + } else { + printer->Print( + variables_, + " $oneof_name$_ = value ?? $default_value$;\n" + " $oneof_name$Case_ = value == null ? $oneof_property_name$Case.None : $oneof_property_name$Case.$property_name$;\n"); + } printer->Print( - variables_, - "public bool Has$property_name$ {\n" - " get { return result.$has_property_check$; }\n" + " }\n" "}\n"); - } - AddPublicMemberAttributes(printer); - printer->Print( - variables_, - "public $type_name$ $property_name$ {\n" - " get { return result.$has_property_check$ ? ($type_name$) result.$oneof_name$_ : $default_value$; }\n" - " set { Set$property_name$(value); }\n" - "}\n"); - AddPublicMemberAttributes(printer); - printer->Print( - variables_, - "public Builder Set$property_name$($type_name$ value) {\n"); - AddNullCheck(printer); - printer->Print( - variables_, - " PrepareBuilder();\n" - " result.$oneof_name$_ = value;\n" - " result.$oneof_name$Case_ = $oneof_property_name$OneofCase.$property_name$;\n" - " return this;\n" - "}\n"); - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public Builder Clear$property_name$() {\n" - " PrepareBuilder();\n" - " if (result.$has_property_check$) {\n" - " result.$oneof_name$Case_ = $oneof_property_name$OneofCase.None;\n" - " }\n" - " return this;\n" - "}\n"); } -void PrimitiveOneofFieldGenerator::WriteEquals(io::Printer* printer) { - printer->Print( - variables_, - "if (!$property_name$.Equals(other.$property_name$)) return false;\n"); -} void PrimitiveOneofFieldGenerator::WriteToString(io::Printer* printer) { printer->Print(variables_, "PrintField(\"$descriptor_name$\", $has_property_check$, $oneof_name$_, writer);\n"); } void PrimitiveOneofFieldGenerator::GenerateParsingCode(io::Printer* printer) { + // TODO(jonskeet): What if the value we read is the default value for the type? printer->Print( variables_, "$type_name$ value = $default_value$;\n" "if (input.Read$capitalized_type_name$(ref value)) {\n" - " result.$oneof_name$_ = value;\n" - " result.$oneof_name$Case_ = $oneof_property_name$OneofCase.$property_name$;\n" + " $oneof_name$_ = value;\n" + " $oneof_name$Case_ = $oneof_property_name$OneofCase.$property_name$;\n" "}\n"); } diff --git a/src/google/protobuf/compiler/csharp/csharp_primitive_field.h b/src/google/protobuf/compiler/csharp/csharp_primitive_field.h index 8a2d5020..d6672b6c 100644 --- a/src/google/protobuf/compiler/csharp/csharp_primitive_field.h +++ b/src/google/protobuf/compiler/csharp/csharp_primitive_field.h @@ -41,17 +41,13 @@ namespace protobuf { namespace compiler { namespace csharp { -class Writer; - class PrimitiveFieldGenerator : public FieldGeneratorBase { public: PrimitiveFieldGenerator(const FieldDescriptor* descriptor, int fieldOrdinal); ~PrimitiveFieldGenerator(); virtual void GenerateMembers(io::Printer* printer); - virtual void GenerateBuilderMembers(io::Printer* printer); virtual void GenerateMergingCode(io::Printer* printer); - virtual void GenerateBuildingCode(io::Printer* printer); virtual void GenerateParsingCode(io::Printer* printer); virtual void GenerateSerializationCode(io::Printer* printer); virtual void GenerateSerializedSizeCode(io::Printer* printer); @@ -60,6 +56,9 @@ class PrimitiveFieldGenerator : public FieldGeneratorBase { virtual void WriteEquals(io::Printer* printer); virtual void WriteToString(io::Printer* printer); + protected: + bool is_value_type; + private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(PrimitiveFieldGenerator); }; @@ -70,8 +69,6 @@ class PrimitiveOneofFieldGenerator : public PrimitiveFieldGenerator { ~PrimitiveOneofFieldGenerator(); virtual void GenerateMembers(io::Printer* printer); - virtual void GenerateBuilderMembers(io::Printer* printer); - virtual void WriteEquals(io::Printer* printer); virtual void WriteToString(io::Printer* printer); virtual void GenerateParsingCode(io::Printer* printer); diff --git a/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc b/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc index f5ebcfb1..f5d5a126 100644 --- a/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc @@ -56,141 +56,46 @@ RepeatedEnumFieldGenerator::~RepeatedEnumFieldGenerator() { } void RepeatedEnumFieldGenerator::GenerateMembers(io::Printer* printer) { - if (descriptor_->is_packed() && optimize_speed()) { - printer->Print(variables_, "private int $name$MemoizedSerializedSize;\n"); - } - printer->Print(variables_, - "private pbc::PopsicleList<$type_name$> $name$_ = new pbc::PopsicleList<$type_name$>();\n"); - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public scg::IList<$type_name$> $property_name$List {\n" - " get { return pbc::Lists.AsReadOnly($name$_); }\n" - "}\n"); - - // TODO(jonskeet): Redundant API calls? Possibly - include for portability though. Maybe create an option. - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public int $property_name$Count {\n" - " get { return $name$_.Count; }\n" - "}\n"); - - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public $type_name$ Get$property_name$(int index) {\n" - " return $name$_[index];\n" - "}\n"); -} - -void RepeatedEnumFieldGenerator::GenerateBuilderMembers(io::Printer* printer) { - // Note: We can return the original list here, because we make it unmodifiable when we build - // We return it via IPopsicleList so that collection initializers work more pleasantly. - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public pbc::IPopsicleList<$type_name$> $property_name$List {\n" - " get { return PrepareBuilder().$name$_; }\n" - "}\n"); - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public int $property_name$Count {\n" - " get { return result.$property_name$Count; }\n" - "}\n"); - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public $type_name$ Get$property_name$(int index) {\n" - " return result.Get$property_name$(index);\n" - "}\n"); - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public Builder Set$property_name$(int index, $type_name$ value) {\n"); - printer->Print( - variables_, - " PrepareBuilder();\n" - " result.$name$_[index] = value;\n" - " return this;\n" - "}\n"); - AddDeprecatedFlag(printer); printer->Print(variables_, - "public Builder Add$property_name$($type_name$ value) {\n"); - printer->Print( - variables_, - " PrepareBuilder();\n" - " result.$name$_.Add(value);\n" - " return this;\n" - "}\n"); - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public Builder AddRange$property_name$(scg::IEnumerable<$type_name$> values) {\n" - " PrepareBuilder();\n" - " result.$name$_.Add(values);\n" - " return this;\n" - "}\n"); + "private readonly pbc::RepeatedField<$type_name$> $name$_ = new pbc::RepeatedField<$type_name$>();\n"); AddDeprecatedFlag(printer); printer->Print( variables_, - "public Builder Clear$property_name$() {\n" - " PrepareBuilder();\n" - " result.$name$_.Clear();\n" - " return this;\n" + "public pbc::RepeatedField<$type_name$> $property_name$ {\n" + " get { return $name$_; }\n" "}\n"); } void RepeatedEnumFieldGenerator::GenerateMergingCode(io::Printer* printer) { printer->Print( variables_, - "if (other.$name$_.Count != 0) {\n" - " result.$name$_.Add(other.$name$_);\n" - "}\n"); -} - -void RepeatedEnumFieldGenerator::GenerateBuildingCode(io::Printer* printer) { - printer->Print(variables_, "$name$_.MakeReadOnly();\n"); + "$name$_.Add(other.$name$_);\n"); } void RepeatedEnumFieldGenerator::GenerateParsingCode(io::Printer* printer) { printer->Print( variables_, - "scg::ICollection unknownItems;\n" - "input.ReadEnumArray<$type_name$>(tag, field_name, result.$name$_, out unknownItems);\n"); - if (!use_lite_runtime()) { - printer->Print( - variables_, - "if (unknownItems != null) {\n" - " if (unknownFields == null) {\n" - " unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);\n" - " }\n" - " foreach (object rawValue in unknownItems)\n" - " if (rawValue is int)\n" - " unknownFields.MergeVarintField($number$, (ulong)(int)rawValue);\n" - "}\n"); - } + "input.ReadEnumArray<$type_name$>(tag, fieldName, result.$name$_);\n"); } void RepeatedEnumFieldGenerator::GenerateSerializationCode(io::Printer* printer) { - printer->Print(variables_, "if ($name$_.Count > 0) {\n"); - printer->Indent(); + // TODO(jonskeet): Originally, this checked for Count > 0 first. + // The Write* call should make that cheap though - no need to generate it every time. if (descriptor_->is_packed()) { printer->Print( variables_, - "output.WritePackedEnumArray($number$, field_names[$field_ordinal$], $name$MemoizedSerializedSize, $name$_);\n"); + "output.WritePackedEnumArray($number$, fieldNames[$field_ordinal$], $name$_);\n"); } else { printer->Print(variables_, - "output.WriteEnumArray($number$, field_names[$field_ordinal$], $name$_);\n"); + "output.WriteEnumArray($number$, fieldNames[$field_ordinal$], $name$_);\n"); } - printer->Outdent(); printer->Print("}\n"); } void RepeatedEnumFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { printer->Print("{\n"); printer->Indent(); + // TODO(jonskeet): Move all this code into CodedOutputStream? It's a lot to repeat everywhere... printer->Print( variables_, "int dataSize = 0;\n" @@ -199,7 +104,7 @@ void RepeatedEnumFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer printer->Print( variables_, "foreach ($type_name$ element in $name$_) {\n" - " dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag((int) element);\n" + " dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag((long) element);\n" "}\n" "size += dataSize;\n"); int tagSize = internal::WireFormat::TagSize(descriptor_->number(), descriptor_->type()); @@ -215,11 +120,6 @@ void RepeatedEnumFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer } printer->Outdent(); printer->Print("}\n"); - // cache the data size for packed fields. - if (descriptor_->is_packed()) { - printer->Print(variables_, - "$name$MemoizedSerializedSize = dataSize;\n"); - } printer->Outdent(); printer->Print("}\n"); } @@ -227,16 +127,15 @@ void RepeatedEnumFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer void RepeatedEnumFieldGenerator::WriteHash(io::Printer* printer) { printer->Print( variables_, - "foreach($type_name$ i in $name$_)\n" - " hash ^= i.GetHashCode();\n"); + "foreach($type_name$ i in $name$_) {\n" + " hash ^= i.GetHashCode();\n" + "}\n"); } void RepeatedEnumFieldGenerator::WriteEquals(io::Printer* printer) { printer->Print( variables_, - "if($name$_.Count != other.$name$_.Count) return false;\n" - "for(int ix=0; ix < $name$_.Count; ix++)\n" - " if(!$name$_[ix].Equals(other.$name$_[ix])) return false;\n"); + "if(!$name$_.Equals(other.$name$)) return false;\n"); } void RepeatedEnumFieldGenerator::WriteToString(io::Printer* printer) { diff --git a/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.h b/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.h index 68c3d6c9..92f265c5 100644 --- a/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.h +++ b/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.h @@ -41,17 +41,15 @@ namespace protobuf { namespace compiler { namespace csharp { -class Writer; - +// TODO(jonskeet): Refactor repeated field support; all the implementations are *really* similar. We +// should probably have a RepeatedFieldGeneratorBase. class RepeatedEnumFieldGenerator : public FieldGeneratorBase { public: RepeatedEnumFieldGenerator(const FieldDescriptor* descriptor, int fieldOrdinal); ~RepeatedEnumFieldGenerator(); virtual void GenerateMembers(io::Printer* printer); - virtual void GenerateBuilderMembers(io::Printer* printer); virtual void GenerateMergingCode(io::Printer* printer); - virtual void GenerateBuildingCode(io::Printer* printer); virtual void GenerateParsingCode(io::Printer* printer); virtual void GenerateSerializationCode(io::Printer* printer); virtual void GenerateSerializedSizeCode(io::Printer* printer); diff --git a/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc b/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc index 2ae1d579..2a6a01f5 100644 --- a/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc @@ -48,7 +48,6 @@ namespace csharp { RepeatedMessageFieldGenerator::RepeatedMessageFieldGenerator( const FieldDescriptor* descriptor, int fieldOrdinal) : FieldGeneratorBase(descriptor, fieldOrdinal) { - variables_["message_or_group"] = message_or_group(); } RepeatedMessageFieldGenerator::~RepeatedMessageFieldGenerator() { @@ -58,11 +57,11 @@ RepeatedMessageFieldGenerator::~RepeatedMessageFieldGenerator() { void RepeatedMessageFieldGenerator::GenerateMembers(io::Printer* printer) { printer->Print( variables_, - "private pbc::PopsicleList<$type_name$> $name$_ = new pbc::PopsicleList<$type_name$>();\n"); + "private readonly pbc::RepeatedField<$type_name$> $name$_ = new pbc::RepeatedField<$type_name$>();\n"); AddDeprecatedFlag(printer); printer->Print( variables_, - "public scg::IList<$type_name$> $property_name$List {\n" + "public pbc::RepeatedField<$type_name$> $property_name$ {\n" " get { return $name$_; }\n" "}\n"); @@ -82,137 +81,46 @@ void RepeatedMessageFieldGenerator::GenerateMembers(io::Printer* printer) { "}\n"); } -void RepeatedMessageFieldGenerator::GenerateBuilderMembers(io::Printer* printer) { - // Note: We can return the original list here, because we make it unmodifiable when we build - // We return it via IPopsicleList so that collection initializers work more pleasantly. - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public pbc::IPopsicleList<$type_name$> $property_name$List {\n" - " get { return PrepareBuilder().$name$_; }\n" - "}\n"); - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public int $property_name$Count {\n" - " get { return result.$property_name$Count; }\n" - "}\n"); - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public $type_name$ Get$property_name$(int index) {\n" - " return result.Get$property_name$(index);\n" - "}\n"); - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public Builder Set$property_name$(int index, $type_name$ value) {\n"); - AddNullCheck(printer); - printer->Print( - variables_, - " PrepareBuilder();\n" - " result.$name$_[index] = value;\n" - " return this;\n" - "}\n"); - // Extra overload for builder (just on messages) - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public Builder Set$property_name$(int index, $type_name$.Builder builderForValue) {\n"); - AddNullCheck(printer, "builderForValue"); - printer->Print( - variables_, - " PrepareBuilder();\n" - " result.$name$_[index] = builderForValue.Build();\n" - " return this;\n" - "}\n"); - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public Builder Add$property_name$($type_name$ value) {\n"); - AddNullCheck(printer); - printer->Print( - variables_, - " PrepareBuilder();\n" - " result.$name$_.Add(value);\n" - " return this;\n" - "}\n"); - // Extra overload for builder (just on messages) - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public Builder Add$property_name$($type_name$.Builder builderForValue) {\n"); - AddNullCheck(printer, "builderForValue"); - printer->Print( - variables_, - " PrepareBuilder();\n" - " result.$name$_.Add(builderForValue.Build());\n" - " return this;\n" - "}\n"); - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public Builder AddRange$property_name$(scg::IEnumerable<$type_name$> values) {\n" - " PrepareBuilder();\n" - " result.$name$_.Add(values);\n" - " return this;\n" - "}\n"); - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public Builder Clear$property_name$() {\n" - " PrepareBuilder();\n" - " result.$name$_.Clear();\n" - " return this;\n" - "}\n"); -} - void RepeatedMessageFieldGenerator::GenerateMergingCode(io::Printer* printer) { printer->Print( variables_, - "if (other.$name$_.Count != 0) {\n" - " result.$name$_.Add(other.$name$_);\n" - "}\n"); -} - -void RepeatedMessageFieldGenerator::GenerateBuildingCode(io::Printer* printer) { - printer->Print(variables_, "$name$_.MakeReadOnly();\n"); + "$name$_.Add(other.$name$_);\n"); } void RepeatedMessageFieldGenerator::GenerateParsingCode(io::Printer* printer) { printer->Print( variables_, - "input.Read$message_or_group$Array(tag, field_name, result.$name$_, $type_name$.DefaultInstance, extensionRegistry);\n"); + "input.ReadMessageArray(tag, fieldName, $name$_);\n"); } void RepeatedMessageFieldGenerator::GenerateSerializationCode(io::Printer* printer) { + // TODO(jonskeet): Originally, this checked for Count > 0 first. + // The Write* call should make that cheap though - no need to generate it every time. printer->Print( variables_, - "if ($name$_.Count > 0) {\n" - " output.Write$message_or_group$Array($number$, field_names[$field_ordinal$], $name$_);\n" - "}\n"); + "output.WriteMessageArray($number$, fieldNames[$field_ordinal$], $name$_);\n"); } void RepeatedMessageFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { + // TODO(jonskeet): Put this into CodedOutputStream. printer->Print( variables_, - "foreach ($type_name$ element in $property_name$List) {\n" - " size += pb::CodedOutputStream.Compute$message_or_group$Size($number$, element);\n" + "foreach ($type_name$ element in $property_name$) {\n" + " size += pb::CodedOutputStream.ComputeMessageSize($number$, element);\n" "}\n"); } void RepeatedMessageFieldGenerator::WriteHash(io::Printer* printer) { printer->Print( variables_, - "foreach($type_name$ i in $name$_)\n" - " hash ^= i.GetHashCode();\n"); + "foreach($type_name$ i in $name$_) {\n" + " hash ^= i.GetHashCode();\n" + "}\n"); } void RepeatedMessageFieldGenerator::WriteEquals(io::Printer* printer) { printer->Print( variables_, - "if($name$_.Count != other.$name$_.Count) return false;\n" - "for(int ix=0; ix < $name$_.Count; ix++)\n" - " if(!$name$_[ix].Equals(other.$name$_[ix])) return false;\n"); + "if(!$name$_.Equals(other.$name$)) return false;\n"); } void RepeatedMessageFieldGenerator::WriteToString(io::Printer* printer) { variables_["field_name"] = GetFieldName(descriptor_); diff --git a/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.h b/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.h index 9db76939..b8582800 100644 --- a/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.h +++ b/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.h @@ -41,17 +41,13 @@ namespace protobuf { namespace compiler { namespace csharp { -class Writer; - class RepeatedMessageFieldGenerator : public FieldGeneratorBase { public: RepeatedMessageFieldGenerator(const FieldDescriptor* descriptor, int fieldOrdinal); ~RepeatedMessageFieldGenerator(); virtual void GenerateMembers(io::Printer* printer); - virtual void GenerateBuilderMembers(io::Printer* printer); virtual void GenerateMergingCode(io::Printer* printer); - virtual void GenerateBuildingCode(io::Printer* printer); virtual void GenerateParsingCode(io::Printer* printer); virtual void GenerateSerializationCode(io::Printer* printer); virtual void GenerateSerializedSizeCode(io::Printer* printer); diff --git a/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc b/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc index e27458bb..2001b849 100644 --- a/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc @@ -56,129 +56,43 @@ RepeatedPrimitiveFieldGenerator::~RepeatedPrimitiveFieldGenerator() { } void RepeatedPrimitiveFieldGenerator::GenerateMembers(io::Printer* printer) { - if (descriptor_->is_packed() && optimize_speed()) { - printer->Print(variables_, "private int $name$MemoizedSerializedSize;\n"); - } printer->Print(variables_, - "private pbc::PopsicleList<$type_name$> $name$_ = new pbc::PopsicleList<$type_name$>();\n"); - AddPublicMemberAttributes(printer); - printer->Print( - variables_, - "public scg::IList<$type_name$> $property_name$List {\n" - " get { return pbc::Lists.AsReadOnly($name$_); }\n" - "}\n"); - - // TODO(jonskeet): Redundant API calls? Possibly - include for portability though. Maybe create an option. + "private readonly pbc::RepeatedField<$type_name$> $name$_ = new pbc::RepeatedField<$type_name$>();\n"); AddDeprecatedFlag(printer); printer->Print( variables_, - "public int $property_name$Count {\n" - " get { return $name$_.Count; }\n" - "}\n"); - - AddPublicMemberAttributes(printer); - printer->Print( - variables_, - "public $type_name$ Get$property_name$(int index) {\n" - " return $name$_[index];\n" - "}\n"); -} - -void RepeatedPrimitiveFieldGenerator::GenerateBuilderMembers(io::Printer* printer) { - // Note: We can return the original list here, because we make it unmodifiable when we build - // We return it via IPopsicleList so that collection initializers work more pleasantly. - AddPublicMemberAttributes(printer); - printer->Print( - variables_, - "public pbc::IPopsicleList<$type_name$> $property_name$List {\n" - " get { return PrepareBuilder().$name$_; }\n" - "}\n"); - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public int $property_name$Count {\n" - " get { return result.$property_name$Count; }\n" - "}\n"); - AddPublicMemberAttributes(printer); - printer->Print( - variables_, - "public $type_name$ Get$property_name$(int index) {\n" - " return result.Get$property_name$(index);\n" - "}\n"); - AddPublicMemberAttributes(printer); - printer->Print( - variables_, - "public Builder Set$property_name$(int index, $type_name$ value) {\n"); - AddNullCheck(printer); - printer->Print( - variables_, - " PrepareBuilder();\n" - " result.$name$_[index] = value;\n" - " return this;\n" - "}\n"); - AddPublicMemberAttributes(printer); - printer->Print( - variables_, - "public Builder Add$property_name$($type_name$ value) {\n"); - AddNullCheck(printer); - printer->Print( - variables_, - " PrepareBuilder();\n" - " result.$name$_.Add(value);\n" - " return this;\n" - "}\n"); - AddPublicMemberAttributes(printer); - printer->Print( - variables_, - "public Builder AddRange$property_name$(scg::IEnumerable<$type_name$> values) {\n" - " PrepareBuilder();\n" - " result.$name$_.Add(values);\n" - " return this;\n" - "}\n"); - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public Builder Clear$property_name$() {\n" - " PrepareBuilder();\n" - " result.$name$_.Clear();\n" - " return this;\n" + "public pbc::RepeatedField<$type_name$> $property_name$ {\n" + " get { return $name$_; }\n" "}\n"); } void RepeatedPrimitiveFieldGenerator::GenerateMergingCode(io::Printer* printer) { printer->Print( variables_, - "if (other.$name$_.Count != 0) {\n" - " result.$name$_.Add(other.$name$_);\n" - "}\n"); -} - -void RepeatedPrimitiveFieldGenerator::GenerateBuildingCode(io::Printer* printer) { - printer->Print(variables_, "$name$_.MakeReadOnly();\n"); + "$name$_.Add(other.$name$_);\n"); } void RepeatedPrimitiveFieldGenerator::GenerateParsingCode(io::Printer* printer) { printer->Print(variables_, - "input.Read$capitalized_type_name$Array(tag, field_name, result.$name$_);\n"); + "input.Read$capitalized_type_name$Array(tag, fieldName, $name$_);\n"); } void RepeatedPrimitiveFieldGenerator::GenerateSerializationCode( io::Printer* printer) { - printer->Print(variables_, "if ($name$_.Count > 0) {\n"); - printer->Indent(); + // TODO(jonskeet): Originally, this checked for Count > 0 first. + // The Write* call should make that cheap though - no need to generate it every time. if (descriptor_->is_packed()) { printer->Print(variables_, - "output.WritePacked$capitalized_type_name$Array($number$, field_names[$field_ordinal$], $name$MemoizedSerializedSize, $name$_);\n"); + "output.WritePacked$capitalized_type_name$Array($number$, fieldNames[$field_ordinal$], $name$_);\n"); } else { printer->Print(variables_, - "output.Write$capitalized_type_name$Array($number$, field_names[$field_ordinal$], $name$_);\n"); + "output.Write$capitalized_type_name$Array($number$, fieldNames[$field_ordinal$], $name$_);\n"); } - printer->Outdent(); - printer->Print("}\n"); } void RepeatedPrimitiveFieldGenerator::GenerateSerializedSizeCode( io::Printer* printer) { + // TODO(jonskeet): Get rid of most of this - move it into the runtime. printer->Print("{\n"); printer->Indent(); printer->Print("int dataSize = 0;\n"); @@ -207,10 +121,6 @@ void RepeatedPrimitiveFieldGenerator::GenerateSerializedSizeCode( "size += $tag_size$ * $name$_.Count;\n", "tag_size", SimpleItoa(tagSize), "name", name()); } - // cache the data size for packed fields. - if (descriptor_->is_packed()) { - printer->Print(variables_, "$name$MemoizedSerializedSize = dataSize;\n"); - } printer->Outdent(); printer->Print("}\n"); } @@ -218,15 +128,14 @@ void RepeatedPrimitiveFieldGenerator::GenerateSerializedSizeCode( void RepeatedPrimitiveFieldGenerator::WriteHash(io::Printer* printer) { printer->Print( variables_, - "foreach($type_name$ i in $name$_)\n" - " hash ^= i.GetHashCode();\n"); + "foreach($type_name$ i in $name$_)\n {" + " hash ^= i.GetHashCode();\n" + "}\n"); } void RepeatedPrimitiveFieldGenerator::WriteEquals(io::Printer* printer) { printer->Print( variables_, - "if($name$_.Count != other.$name$_.Count) return false;\n" - "for(int ix=0; ix < $name$_.Count; ix++)\n" - " if(!$name$_[ix].Equals(other.$name$_[ix])) return false;\n"); + "if(!$name$_.Equals(other.$name$)) return false;\n"); } void RepeatedPrimitiveFieldGenerator::WriteToString(io::Printer* printer) { printer->Print(variables_, diff --git a/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.h b/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.h index 50af9dda..29d437d7 100644 --- a/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.h +++ b/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.h @@ -41,17 +41,13 @@ namespace protobuf { namespace compiler { namespace csharp { -class Writer; - class RepeatedPrimitiveFieldGenerator : public FieldGeneratorBase { public: RepeatedPrimitiveFieldGenerator(const FieldDescriptor* descriptor, int fieldOrdinal); ~RepeatedPrimitiveFieldGenerator(); virtual void GenerateMembers(io::Printer* printer); - virtual void GenerateBuilderMembers(io::Printer* printer); virtual void GenerateMergingCode(io::Printer* printer); - virtual void GenerateBuildingCode(io::Printer* printer); virtual void GenerateParsingCode(io::Printer* printer); virtual void GenerateSerializationCode(io::Printer* printer); virtual void GenerateSerializedSizeCode(io::Printer* printer); diff --git a/src/google/protobuf/compiler/csharp/csharp_source_generator_base.cc b/src/google/protobuf/compiler/csharp/csharp_source_generator_base.cc index c52f6092..c666c820 100644 --- a/src/google/protobuf/compiler/csharp/csharp_source_generator_base.cc +++ b/src/google/protobuf/compiler/csharp/csharp_source_generator_base.cc @@ -47,14 +47,6 @@ namespace csharp { SourceGeneratorBase::SourceGeneratorBase(const FileDescriptor* descriptor) : descriptor_(descriptor) { - optimizeSize_ = (descriptor->options().optimize_for() - == FileOptions::CODE_SIZE); - optimizeSpeed_ = (descriptor->options().optimize_for() == FileOptions::SPEED); - useLiteRuntime_ = (descriptor->options().optimize_for() - == FileOptions::LITE_RUNTIME); - - optimizeSpeed_ |= useLiteRuntime_; - runtimeSuffix_ = useLiteRuntime_ ? "Lite" : ""; } SourceGeneratorBase::~SourceGeneratorBase() { diff --git a/src/google/protobuf/compiler/csharp/csharp_source_generator_base.h b/src/google/protobuf/compiler/csharp/csharp_source_generator_base.h index 61c19511..6caef171 100644 --- a/src/google/protobuf/compiler/csharp/csharp_source_generator_base.h +++ b/src/google/protobuf/compiler/csharp/csharp_source_generator_base.h @@ -47,27 +47,10 @@ class SourceGeneratorBase { std::string class_access_level(); - bool optimize_size() { - return optimizeSize_; - } - bool optimize_speed() { - return optimizeSpeed_; - } - bool use_lite_runtime() { - return useLiteRuntime_; - } - std::string runtime_suffix() { - return runtimeSuffix_; - } - void WriteGeneratedCodeAttributes(io::Printer* printer); private: const FileDescriptor* descriptor_; - bool optimizeSize_; - bool optimizeSpeed_; - bool useLiteRuntime_; - std::string runtimeSuffix_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(SourceGeneratorBase); }; diff --git a/src/google/protobuf/compiler/csharp/csharp_umbrella_class.cc b/src/google/protobuf/compiler/csharp/csharp_umbrella_class.cc index b14bf5e8..03a3b8df 100644 --- a/src/google/protobuf/compiler/csharp/csharp_umbrella_class.cc +++ b/src/google/protobuf/compiler/csharp/csharp_umbrella_class.cc @@ -39,7 +39,6 @@ #include #include -#include #include #include @@ -61,18 +60,6 @@ UmbrellaClassGenerator::~UmbrellaClassGenerator() { void UmbrellaClassGenerator::Generate(io::Printer* printer) { WriteIntroduction(printer); - WriteExtensionRegistration(printer); - - // write children: Extensions - if (file_->extension_count() > 0) { - printer->Print("#region Extensions\n"); - for (int i = 0; i < file_->extension_count(); i++) { - ExtensionGenerator extensionGenerator(file_->extension(i)); - extensionGenerator.Generate(printer); - } - printer->Print("#endregion\n"); - printer->Print("\n"); - } printer->Print("#region Static variables\n"); for (int i = 0; i < file_->message_type_count(); i++) { @@ -80,11 +67,7 @@ void UmbrellaClassGenerator::Generate(io::Printer* printer) { messageGenerator.GenerateStaticVariables(printer); } printer->Print("#endregion\n"); - if (!use_lite_runtime()) { - WriteDescriptor(printer); - } else { - WriteLiteExtensions(printer); - } + WriteDescriptor(printer); // Close the class declaration. printer->Outdent(); printer->Print("}\n"); @@ -134,9 +117,9 @@ void UmbrellaClassGenerator::WriteIntroduction(io::Printer* printer) { "#pragma warning disable 1591, 0612, 3021\n" "#region Designer generated code\n" "\n" - "using pb = global::Google.ProtocolBuffers;\n" - "using pbc = global::Google.ProtocolBuffers.Collections;\n" - "using pbd = global::Google.ProtocolBuffers.Descriptors;\n" + "using pb = global::Google.Protobuf;\n" + "using pbc = global::Google.Protobuf.Collections;\n" + "using pbd = global::Google.Protobuf.Descriptors;\n" "using scg = global::System.Collections.Generic;\n", "file_name", file_->name()); @@ -165,24 +148,6 @@ void UmbrellaClassGenerator::WriteIntroduction(io::Printer* printer) { printer->Indent(); } -void UmbrellaClassGenerator::WriteExtensionRegistration(io::Printer* printer) { - printer->Print( - "#region Extension registration\n" - "public static void RegisterAllExtensions(pb::ExtensionRegistry registry) {\n"); - printer->Indent(); - for (int i = 0; i < file_->extension_count(); i++) { - ExtensionGenerator extensionGenerator(file_->extension(i)); - extensionGenerator.GenerateExtensionRegistrationCode(printer); - } - for (int i = 0; i < file_->message_type_count(); i++) { - MessageGenerator messageGenerator(file_->message_type(i)); - messageGenerator.GenerateExtensionRegistrationCode(printer); - } - printer->Outdent(); - printer->Print("}\n"); - printer->Print("#endregion\n"); -} - void UmbrellaClassGenerator::WriteDescriptor(io::Printer* printer) { printer->Print( "#region Descriptor\n" @@ -219,25 +184,7 @@ void UmbrellaClassGenerator::WriteDescriptor(io::Printer* printer) { MessageGenerator messageGenerator(file_->message_type(i)); messageGenerator.GenerateStaticVariableInitializers(printer); } - for (int i = 0; i < file_->extension_count(); i++) { - ExtensionGenerator extensionGenerator(file_->extension(i)); - extensionGenerator.GenerateStaticVariableInitializers(printer); - } - if (uses_extensions()) { - // Must construct an ExtensionRegistry containing all possible extensions - // and return it. - printer->Print( - "pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance();\n"); - printer->Print("RegisterAllExtensions(registry);\n"); - for (int i = 0; i < file_->dependency_count(); i++) { - printer->Print("$dependency$.RegisterAllExtensions(registry);\n", - "dependency", GetFullUmbrellaClassName(file_->dependency(i))); - } - printer->Print("return registry;\n"); - } else { - printer->Print("return null;\n"); - } printer->Outdent(); printer->Print("};\n"); @@ -258,33 +205,6 @@ void UmbrellaClassGenerator::WriteDescriptor(io::Printer* printer) { printer->Print("#endregion\n\n"); } -void UmbrellaClassGenerator::WriteLiteExtensions(io::Printer* printer) { - printer->Print( - "#region Extensions\n" - "internal static readonly object Descriptor;\n" - "static $umbrella_class_name$() {\n", - "umbrella_class_name", umbrellaClassname_); - printer->Indent(); - printer->Print("Descriptor = null;\n"); - for (int i = 0; i < file_->message_type_count(); i++) { - MessageGenerator messageGenerator(file_->message_type(i)); - messageGenerator.GenerateStaticVariableInitializers(printer); - } - for (int i = 0; i < file_->extension_count(); i++) { - ExtensionGenerator extensionGenerator(file_->extension(i)); - extensionGenerator.GenerateStaticVariableInitializers(printer); - } - printer->Outdent(); - printer->Print("}\n"); - printer->Print("#endregion\n\n"); -} - -bool UmbrellaClassGenerator::uses_extensions() { - // TODO(jtattermusch): implement recursive descent that looks for extensions. - // For now, we conservatively assume that extensions are used. - return true; -} - } // namespace csharp } // namespace compiler } // namespace protobuf diff --git a/src/google/protobuf/compiler/csharp/csharp_umbrella_class.h b/src/google/protobuf/compiler/csharp/csharp_umbrella_class.h index 83e1f347..f7533d2d 100644 --- a/src/google/protobuf/compiler/csharp/csharp_umbrella_class.h +++ b/src/google/protobuf/compiler/csharp/csharp_umbrella_class.h @@ -41,8 +41,6 @@ namespace protobuf { namespace compiler { namespace csharp { -class Writer; - class UmbrellaClassGenerator : public SourceGeneratorBase { public: UmbrellaClassGenerator(const FileDescriptor* file); @@ -58,11 +56,7 @@ class UmbrellaClassGenerator : public SourceGeneratorBase { std::string umbrellaNamespace_; void WriteIntroduction(io::Printer* printer); - void WriteExtensionRegistration(io::Printer* printer); void WriteDescriptor(io::Printer* printer); - void WriteLiteExtensions(io::Printer* printer); - - bool uses_extensions(); GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(UmbrellaClassGenerator); }; @@ -73,4 +67,3 @@ class UmbrellaClassGenerator : public SourceGeneratorBase { } // namespace google #endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_UMBRELLA_CLASS_H__ - diff --git a/src/google/protobuf/compiler/csharp/csharp_writer.cc b/src/google/protobuf/compiler/csharp/csharp_writer.cc deleted file mode 100644 index 2bcafde5..00000000 --- a/src/google/protobuf/compiler/csharp/csharp_writer.cc +++ /dev/null @@ -1,136 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// 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. - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -Writer::Writer(google::protobuf::io::Printer* printer) - : printer_(printer), - newline_("\n") { - // TODO(jtattermusch): make newline customizable. -} - -Writer::~Writer() { -} - -void Writer::Indent() { - printer_->Indent(); -} - -void Writer::Outdent() { - printer_->Outdent(); -} - -void Writer::Write(const char* text) { - printer_->Print(text); -} - -void Writer::Write(const char* text, const string& value0) { - printer_->Print(text, "0", value0); -} - -void Writer::Write(const char* text, const string& value0, - const string& value1) { - printer_->Print(text, "0", value0, "1", value1); -} - -void Writer::Write(const char* text, const string& value0, const string& value1, - const string& value2) { - printer_->Print(text, "0", value0, "1", value1, "2", value2); -} - -void Writer::Write(const char* text, const string& value0, const string& value1, - const string& value2, const string& value3) { - printer_->Print(text, "0", value0, "1", value1, "2", value2, "3", value3); -} - -void Writer::WriteLine() { - printer_->Print(newline_); -} - -void Writer::WriteLine(const char* text) { - Write(text); - WriteLine(); -} - -void Writer::WriteLine(const char* text, const string& value0) { - Write(text, value0); - WriteLine(); -} - -void Writer::WriteLine(const char* text, const string& value0, - const string& value1) { - Write(text, value0, value1); - WriteLine(); -} - -void Writer::WriteLine(const char* text, const string& value0, - const string& value1, const string& value2) { - Write(text, value0, value1, value2); - WriteLine(); -} - -void Writer::WriteLine(const char* text, const string& value0, - const string& value1, const string& value2, - const string& value3) { - Write(text, value0, value1, value2, value3); - WriteLine(); -} - -} // namespace java -} // namespace compiler -} // namespace protobuf -} // namespace google diff --git a/src/google/protobuf/compiler/csharp/csharp_writer.h b/src/google/protobuf/compiler/csharp/csharp_writer.h deleted file mode 100644 index 26c59b31..00000000 --- a/src/google/protobuf/compiler/csharp/csharp_writer.h +++ /dev/null @@ -1,93 +0,0 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// 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. - -#ifndef GOOGLE_PROTOBUF_COMPILER_CSHARP_WRITER_H__ -#define GOOGLE_PROTOBUF_COMPILER_CSHARP_WRITER_H__ - -#include -#include -#include -#include -#include - -namespace google { -namespace protobuf { -namespace compiler { -namespace csharp { - -// Simple wrapper around Printer that supports customizable line endings -// and number-based variables (e.g. $0$). -class Writer { - public: - Writer(io::Printer* printer); - ~Writer(); - - void Indent(); - void Outdent(); - - void Write(const char* text); - - void Write(const char* text, const string& value0); - - void Write(const char* text, const string& value0, const string& value1); - - void Write(const char* text, const string& value0, const string& value1, - const string& value2); - - void Write(const char* text, const string& value0, const string& value1, - const string& value2, const string& value3); - - void WriteLine(); - - void WriteLine(const char* text); - - void WriteLine(const char* text, const string& value0); - - void WriteLine(const char* text, const string& value0, const string& value1); - - void WriteLine(const char* text, const string& value0, const string& value1, - const string& value2); - - void WriteLine(const char* text, const string& value0, const string& value1, - const string& value2, const string& value3); - private: - io::Printer* printer_; - const char* newline_; -}; - -} // namespace csharp -} // namespace compiler -} // namespace protobuf -} // namespace google -#endif // GOOGLE_PROTOBUF_COMPILER_CSHARP_WRITER_H__ -- cgit v1.2.3 From e38294a62d7f37c0661273a9a26fda16d557423f Mon Sep 17 00:00:00 2001 From: Jon Skeet Date: Tue, 9 Jun 2015 19:30:44 +0100 Subject: First pass at the mutable API. Quite a bit more to do - in particular, it's pretty slow right now. --- csharp/protos/extest/unittest_issues.proto | 86 +- .../ProtocolBuffers.Test/AbstractMessageTest.cs | 548 - csharp/src/ProtocolBuffers.Test/ByteStringTest.cs | 2 +- .../ProtocolBuffers.Test/CodedInputStreamTest.cs | 64 +- .../ProtocolBuffers.Test/CodedOutputStreamTest.cs | 23 +- .../Collections/PopsicleListTest.cs | 125 - .../Compatibility/BinaryCompatibilityTests.cs | 18 - .../Compatibility/CompatibilityTests.cs | 227 - .../Compatibility/DictionaryCompatibilityTests.cs | 35 - .../Compatibility/JsonCompatibilityTests.cs | 43 - .../Compatibility/TestResources.cs | 38 - .../Compatibility/TextCompatibilityTests.cs | 35 - .../Compatibility/XmlCompatibilityTests.cs | 45 - .../Compatibility/google_message1.dat | Bin 228 -> 0 bytes .../Compatibility/google_message2.dat | Bin 84570 -> 0 bytes .../ProtocolBuffers.Test/DeprecatedMemberTest.cs | 82 +- csharp/src/ProtocolBuffers.Test/DescriptorsTest.cs | 152 +- .../src/ProtocolBuffers.Test/DynamicMessageTest.cs | 276 - .../ProtocolBuffers.Test/ExtendableMessageTest.cs | 200 - .../src/ProtocolBuffers.Test/FieldPresenceTest.cs | 198 - .../ProtocolBuffers.Test/GeneratedBuilderTest.cs | 102 - .../ProtocolBuffers.Test/GeneratedMessageTest.cs | 911 +- csharp/src/ProtocolBuffers.Test/IssuesTest.cs | 10 +- .../MessageStreamIteratorTest.cs | 90 - .../MessageStreamWriterTest.cs | 78 - csharp/src/ProtocolBuffers.Test/MessageTest.cs | 344 - csharp/src/ProtocolBuffers.Test/MessageUtilTest.cs | 82 - csharp/src/ProtocolBuffers.Test/NameHelpersTest.cs | 81 - .../ProtocolBuffers.Test.csproj | 62 +- .../src/ProtocolBuffers.Test/ReflectionTester.cs | 1033 - .../src/ProtocolBuffers.Test/RepeatedFieldTest.cs | 50 + .../ProtocolBuffers.Test/ReusableBuilderTest.cs | 166 - csharp/src/ProtocolBuffers.Test/TestCornerCases.cs | 22 +- .../ProtocolBuffers.Test/TestMimeMessageFormats.cs | 277 - .../ProtocolBuffers.Test/TestProtos/GoogleSize.cs | 4547 --- .../ProtocolBuffers.Test/TestProtos/GoogleSpeed.cs | 6612 ---- .../ProtocolBuffers.Test/TestProtos/Unittest.cs | 33878 ----------------- .../TestProtos/UnittestCustomOptions.cs | 7543 ---- .../TestProtos/UnittestDropUnknownFields.cs | 732 - .../TestProtos/UnittestEnormousDescriptor.cs | 36189 ------------------- .../TestProtos/UnittestExtrasXmltest.cs | 2277 -- .../TestProtos/UnittestImport.cs | 347 - .../TestProtos/UnittestImportProto3.cs | 165 + .../TestProtos/UnittestImportPublic.cs | 333 - .../TestProtos/UnittestImportPublicProto3.cs | 150 + .../TestProtos/UnittestIssues.cs | 2571 +- .../TestProtos/UnittestMset.cs | 1824 - .../TestProtos/UnittestNoFieldPresence.cs | 3876 -- .../TestProtos/UnittestOptimizeFor.cs | 738 - .../TestProtos/UnittestProto3.cs | 6060 ++++ .../TestProtos/UnknownEnumTest.cs | 809 - .../TestReaderForUrlEncoded.cs | 83 - csharp/src/ProtocolBuffers.Test/TestResources.cs | 301 - csharp/src/ProtocolBuffers.Test/TestUtil.cs | 1862 - .../ProtocolBuffers.Test/TestWriterFormatJson.cs | 498 - .../ProtocolBuffers.Test/TestWriterFormatXml.cs | 468 - csharp/src/ProtocolBuffers.Test/TextFormatTest.cs | 560 - .../ProtocolBuffers.Test/UnknownFieldSetTest.cs | 431 - csharp/src/ProtocolBuffers.Test/WireFormatTest.cs | 255 +- csharp/src/ProtocolBuffers/AbstractBuilder.cs | 274 - csharp/src/ProtocolBuffers/AbstractBuilderLite.cs | 264 - csharp/src/ProtocolBuffers/AbstractMessage.cs | 293 - csharp/src/ProtocolBuffers/AbstractMessageLite.cs | 140 - csharp/src/ProtocolBuffers/ByteArray.cs | 2 +- csharp/src/ProtocolBuffers/ByteString.cs | 20 +- csharp/src/ProtocolBuffers/CodedInputStream.cs | 163 +- .../CodedOutputStream.ComputeSize.cs | 71 +- csharp/src/ProtocolBuffers/CodedOutputStream.cs | 338 +- .../ProtocolBuffers/Collections/Dictionaries.cs | 2 +- .../src/ProtocolBuffers/Collections/Enumerables.cs | 2 +- .../ProtocolBuffers/Collections/IPopsicleList.cs | 58 - csharp/src/ProtocolBuffers/Collections/Lists.cs | 2 +- .../ProtocolBuffers/Collections/PopsicleList.cs | 208 - .../Collections/ReadOnlyDictionary.cs | 2 +- .../ProtocolBuffers/Collections/RepeatedField.cs | 168 + .../Collections/RepeatedFieldExtensions.cs | 47 + csharp/src/ProtocolBuffers/Delegates.cs | 54 - .../DescriptorProtos/DescriptorProtoFile.cs | 12724 ++----- .../DescriptorProtos/IDescriptorProto.cs | 2 +- .../DescriptorProtos/PartialClasses.cs | 2 +- .../ProtocolBuffers/Descriptors/DescriptorBase.cs | 5 +- .../ProtocolBuffers/Descriptors/DescriptorPool.cs | 4 +- .../ProtocolBuffers/Descriptors/DescriptorUtil.cs | 4 +- .../Descriptors/DescriptorValidationException.cs | 13 +- .../ProtocolBuffers/Descriptors/EnumDescriptor.cs | 31 +- .../Descriptors/EnumValueDescriptor.cs | 7 +- .../ProtocolBuffers/Descriptors/FieldDescriptor.cs | 223 +- .../Descriptors/FieldMappingAttribute.cs | 4 +- .../src/ProtocolBuffers/Descriptors/FieldType.cs | 2 +- .../ProtocolBuffers/Descriptors/FileDescriptor.cs | 55 +- .../src/ProtocolBuffers/Descriptors/IDescriptor.cs | 4 +- .../Descriptors/IndexedDescriptorBase.cs | 4 +- .../src/ProtocolBuffers/Descriptors/MappedType.cs | 2 +- .../Descriptors/MessageDescriptor.cs | 30 +- .../Descriptors/MethodDescriptor.cs | 4 +- .../ProtocolBuffers/Descriptors/OneofDescriptor.cs | 4 +- .../Descriptors/PackageDescriptor.cs | 2 +- .../Descriptors/ServiceDescriptor.cs | 8 +- csharp/src/ProtocolBuffers/DynamicMessage.cs | 624 - csharp/src/ProtocolBuffers/EnumHelper.cs | 85 + csharp/src/ProtocolBuffers/EnumLite.cs | 234 - csharp/src/ProtocolBuffers/ExtendableBuilder.cs | 212 - .../src/ProtocolBuffers/ExtendableBuilderLite.cs | 345 - csharp/src/ProtocolBuffers/ExtendableMessage.cs | 274 - .../src/ProtocolBuffers/ExtendableMessageLite.cs | 221 - csharp/src/ProtocolBuffers/ExtensionInfo.cs | 88 - csharp/src/ProtocolBuffers/ExtensionRegistry.cs | 215 - .../src/ProtocolBuffers/ExtensionRegistryLite.cs | 232 - csharp/src/ProtocolBuffers/Extensions.cs | 70 + .../FieldAccess/FieldAccessorBase.cs | 38 + .../FieldAccess/FieldAccessorTable.cs | 104 +- .../ProtocolBuffers/FieldAccess/IFieldAccessor.cs | 59 +- .../ProtocolBuffers/FieldAccess/OneofAccessor.cs | 13 +- .../ProtocolBuffers/FieldAccess/ReflectionUtil.cs | 57 +- .../FieldAccess/RepeatedEnumAccessor.cs | 83 - .../FieldAccess/RepeatedFieldAccessor.cs | 37 + .../FieldAccess/RepeatedMessageAccessor.cs | 97 - .../FieldAccess/RepeatedPrimitiveAccessor.cs | 158 - .../FieldAccess/SingleEnumAccessor.cs | 75 - .../FieldAccess/SingleFieldAccessor.cs | 89 + .../FieldAccess/SingleMessageAccessor.cs | 91 - .../FieldAccess/SinglePrimitiveAccessor.cs | 162 - csharp/src/ProtocolBuffers/FieldSet.cs | 632 - csharp/src/ProtocolBuffers/FrameworkPortability.cs | 2 +- csharp/src/ProtocolBuffers/GeneratedBuilder.cs | 230 - csharp/src/ProtocolBuffers/GeneratedBuilderLite.cs | 100 - .../src/ProtocolBuffers/GeneratedExtensionBase.cs | 185 - .../src/ProtocolBuffers/GeneratedExtensionLite.cs | 354 - csharp/src/ProtocolBuffers/GeneratedMessage.cs | 191 - csharp/src/ProtocolBuffers/GeneratedMessageLite.cs | 182 - .../ProtocolBuffers/GeneratedRepeatExtension.cs | 88 - .../ProtocolBuffers/GeneratedSingleExtension.cs | 65 - csharp/src/ProtocolBuffers/IBuilder.cs | 323 - csharp/src/ProtocolBuffers/IBuilderLite.cs | 213 - csharp/src/ProtocolBuffers/ICodedInputStream.cs | 50 +- csharp/src/ProtocolBuffers/ICodedOutputStream.cs | 103 +- csharp/src/ProtocolBuffers/IMessage.cs | 216 +- csharp/src/ProtocolBuffers/IMessageLite.cs | 188 - .../InvalidProtocolBufferException.cs | 2 +- csharp/src/ProtocolBuffers/LimitedInputStream.cs | 78 + csharp/src/ProtocolBuffers/MessageParser.cs | 57 + .../src/ProtocolBuffers/MessageStreamIterator.cs | 170 - csharp/src/ProtocolBuffers/MessageStreamWriter.cs | 70 - csharp/src/ProtocolBuffers/MessageUtil.cs | 109 - csharp/src/ProtocolBuffers/NameHelpers.cs | 140 - csharp/src/ProtocolBuffers/ProtocolBuffers.csproj | 61 +- csharp/src/ProtocolBuffers/SortedList.cs | 167 - csharp/src/ProtocolBuffers/TextFormat.cs | 893 - csharp/src/ProtocolBuffers/TextGenerator.cs | 2 +- csharp/src/ProtocolBuffers/TextTokenizer.cs | 501 - csharp/src/ProtocolBuffers/ThrowHelper.cs | 2 +- .../UninitializedMessageException.cs | 208 - csharp/src/ProtocolBuffers/UnknownField.cs | 415 - csharp/src/ProtocolBuffers/UnknownFieldSet.cs | 1061 - csharp/src/ProtocolBuffers/WireFormat.cs | 4 +- .../protobuf/compiler/csharp/csharp_enum_field.cc | 8 +- .../protobuf/compiler/csharp/csharp_field_base.cc | 19 +- .../protobuf/compiler/csharp/csharp_message.cc | 99 +- .../protobuf/compiler/csharp/csharp_message.h | 1 + .../compiler/csharp/csharp_message_field.cc | 30 +- .../compiler/csharp/csharp_primitive_field.cc | 16 +- .../compiler/csharp/csharp_repeated_enum_field.cc | 25 +- .../csharp/csharp_repeated_message_field.cc | 27 +- .../csharp/csharp_repeated_primitive_field.cc | 10 +- src/google/protobuf/descriptor.proto | 2 +- src/google/protobuf/unittest_import_proto3.proto | 68 + .../protobuf/unittest_import_public_proto3.proto | 42 + src/google/protobuf/unittest_proto3.proto | 388 + 168 files changed, 11868 insertions(+), 133448 deletions(-) delete mode 100644 csharp/src/ProtocolBuffers.Test/AbstractMessageTest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/Collections/PopsicleListTest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/Compatibility/BinaryCompatibilityTests.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/Compatibility/CompatibilityTests.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/Compatibility/DictionaryCompatibilityTests.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/Compatibility/JsonCompatibilityTests.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/Compatibility/TestResources.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/Compatibility/TextCompatibilityTests.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/Compatibility/XmlCompatibilityTests.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/Compatibility/google_message1.dat delete mode 100644 csharp/src/ProtocolBuffers.Test/Compatibility/google_message2.dat delete mode 100644 csharp/src/ProtocolBuffers.Test/DynamicMessageTest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/ExtendableMessageTest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/FieldPresenceTest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/GeneratedBuilderTest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/MessageStreamIteratorTest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/MessageStreamWriterTest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/MessageTest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/MessageUtilTest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/NameHelpersTest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/ReflectionTester.cs create mode 100644 csharp/src/ProtocolBuffers.Test/RepeatedFieldTest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/ReusableBuilderTest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestMimeMessageFormats.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestProtos/GoogleSize.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestProtos/GoogleSpeed.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestProtos/Unittest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestProtos/UnittestCustomOptions.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestProtos/UnittestDropUnknownFields.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestProtos/UnittestEnormousDescriptor.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestProtos/UnittestExtrasXmltest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImport.cs create mode 100644 csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImportProto3.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImportPublic.cs create mode 100644 csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImportPublicProto3.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestProtos/UnittestMset.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestProtos/UnittestNoFieldPresence.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestProtos/UnittestOptimizeFor.cs create mode 100644 csharp/src/ProtocolBuffers.Test/TestProtos/UnittestProto3.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestProtos/UnknownEnumTest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestReaderForUrlEncoded.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestResources.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestUtil.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestWriterFormatJson.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestWriterFormatXml.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TextFormatTest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/UnknownFieldSetTest.cs delete mode 100644 csharp/src/ProtocolBuffers/AbstractBuilder.cs delete mode 100644 csharp/src/ProtocolBuffers/AbstractBuilderLite.cs delete mode 100644 csharp/src/ProtocolBuffers/AbstractMessage.cs delete mode 100644 csharp/src/ProtocolBuffers/AbstractMessageLite.cs delete mode 100644 csharp/src/ProtocolBuffers/Collections/IPopsicleList.cs delete mode 100644 csharp/src/ProtocolBuffers/Collections/PopsicleList.cs create mode 100644 csharp/src/ProtocolBuffers/Collections/RepeatedField.cs create mode 100644 csharp/src/ProtocolBuffers/Collections/RepeatedFieldExtensions.cs delete mode 100644 csharp/src/ProtocolBuffers/Delegates.cs delete mode 100644 csharp/src/ProtocolBuffers/DynamicMessage.cs create mode 100644 csharp/src/ProtocolBuffers/EnumHelper.cs delete mode 100644 csharp/src/ProtocolBuffers/EnumLite.cs delete mode 100644 csharp/src/ProtocolBuffers/ExtendableBuilder.cs delete mode 100644 csharp/src/ProtocolBuffers/ExtendableBuilderLite.cs delete mode 100644 csharp/src/ProtocolBuffers/ExtendableMessage.cs delete mode 100644 csharp/src/ProtocolBuffers/ExtendableMessageLite.cs delete mode 100644 csharp/src/ProtocolBuffers/ExtensionInfo.cs delete mode 100644 csharp/src/ProtocolBuffers/ExtensionRegistry.cs delete mode 100644 csharp/src/ProtocolBuffers/ExtensionRegistryLite.cs create mode 100644 csharp/src/ProtocolBuffers/Extensions.cs create mode 100644 csharp/src/ProtocolBuffers/FieldAccess/FieldAccessorBase.cs delete mode 100644 csharp/src/ProtocolBuffers/FieldAccess/RepeatedEnumAccessor.cs create mode 100644 csharp/src/ProtocolBuffers/FieldAccess/RepeatedFieldAccessor.cs delete mode 100644 csharp/src/ProtocolBuffers/FieldAccess/RepeatedMessageAccessor.cs delete mode 100644 csharp/src/ProtocolBuffers/FieldAccess/RepeatedPrimitiveAccessor.cs delete mode 100644 csharp/src/ProtocolBuffers/FieldAccess/SingleEnumAccessor.cs create mode 100644 csharp/src/ProtocolBuffers/FieldAccess/SingleFieldAccessor.cs delete mode 100644 csharp/src/ProtocolBuffers/FieldAccess/SingleMessageAccessor.cs delete mode 100644 csharp/src/ProtocolBuffers/FieldAccess/SinglePrimitiveAccessor.cs delete mode 100644 csharp/src/ProtocolBuffers/FieldSet.cs delete mode 100644 csharp/src/ProtocolBuffers/GeneratedBuilder.cs delete mode 100644 csharp/src/ProtocolBuffers/GeneratedBuilderLite.cs delete mode 100644 csharp/src/ProtocolBuffers/GeneratedExtensionBase.cs delete mode 100644 csharp/src/ProtocolBuffers/GeneratedExtensionLite.cs delete mode 100644 csharp/src/ProtocolBuffers/GeneratedMessage.cs delete mode 100644 csharp/src/ProtocolBuffers/GeneratedMessageLite.cs delete mode 100644 csharp/src/ProtocolBuffers/GeneratedRepeatExtension.cs delete mode 100644 csharp/src/ProtocolBuffers/GeneratedSingleExtension.cs delete mode 100644 csharp/src/ProtocolBuffers/IBuilder.cs delete mode 100644 csharp/src/ProtocolBuffers/IBuilderLite.cs delete mode 100644 csharp/src/ProtocolBuffers/IMessageLite.cs create mode 100644 csharp/src/ProtocolBuffers/LimitedInputStream.cs create mode 100644 csharp/src/ProtocolBuffers/MessageParser.cs delete mode 100644 csharp/src/ProtocolBuffers/MessageStreamIterator.cs delete mode 100644 csharp/src/ProtocolBuffers/MessageStreamWriter.cs delete mode 100644 csharp/src/ProtocolBuffers/MessageUtil.cs delete mode 100644 csharp/src/ProtocolBuffers/NameHelpers.cs delete mode 100644 csharp/src/ProtocolBuffers/SortedList.cs delete mode 100644 csharp/src/ProtocolBuffers/TextFormat.cs delete mode 100644 csharp/src/ProtocolBuffers/TextTokenizer.cs delete mode 100644 csharp/src/ProtocolBuffers/UninitializedMessageException.cs delete mode 100644 csharp/src/ProtocolBuffers/UnknownField.cs delete mode 100644 csharp/src/ProtocolBuffers/UnknownFieldSet.cs create mode 100644 src/google/protobuf/unittest_import_proto3.proto create mode 100644 src/google/protobuf/unittest_import_public_proto3.proto create mode 100644 src/google/protobuf/unittest_proto3.proto (limited to 'src/google') diff --git a/csharp/protos/extest/unittest_issues.proto b/csharp/protos/extest/unittest_issues.proto index 97249dff..c123acf1 100644 --- a/csharp/protos/extest/unittest_issues.proto +++ b/csharp/protos/extest/unittest_issues.proto @@ -1,4 +1,4 @@ -syntax = "proto2"; +syntax = "proto3"; // These proto descriptors have at one time been reported as an issue or defect. // They are kept here to replicate the issue, and continue to verify the fix. @@ -9,65 +9,6 @@ option csharp_namespace = "UnitTest.Issues.TestProtos"; package unittest_issues; option optimize_for = SPEED; -// The following is a representative set of features -/* -enum EnumOptions { - ONE = 0; - TWO = 1; - THREE = 2; -} - -message TestBasicChild -{ - repeated EnumOptions options = 3; - optional bytes binary = 4; -} - -message TestBasicNoFields { -} - -message TestBasicRescursive { - optional TestBasicRescursive child = 1; -} - -message TestBasicMessage { - - optional int64 number = 6; - repeated int32 numbers = 2; - optional string text = 3; - repeated string textlines = 700; - optional bool valid = 5; - - optional TestBasicChild child = 1; - repeated group Children = 401 - { - repeated EnumOptions options = 3; - optional bytes binary = 4; - } - - extensions 100 to 199; -} - -message TestBasicExtension { - required int32 number = 1; -} - -extend TestBasicMessage { - optional EnumOptions extension_enum = 101; - optional string extension_text = 102; - repeated int32 extension_number = 103 [packed = true]; - optional TestBasicExtension extension_message = 199; -} - -// Issue for non-qualified type reference in new services generation -option (google.protobuf.csharp_file_options).service_generator_type = IRPCDISPATCH; - -service TestGenericService { - rpc Foo(TestBasicNoFields) returns (TestBasicMessage); - rpc Bar(TestBasicNoFields) returns (TestBasicMessage); -} -*/ - // Old issue 13: http://code.google.com/p/protobuf-csharp-port/issues/detail?id=13 // New issue 309: https://github.com/google/protobuf/issues/309 @@ -90,27 +31,17 @@ service TestGenericService { // optional int32 _01 = 1; // } -// Issue 28: Circular message dependencies result in null defaults for DefaultInstance - -message MyMessageAReferenceB { - required MyMessageBReferenceA value = 1; -} - -message MyMessageBReferenceA { - required MyMessageAReferenceB value = 1; -} - // issue 19 - negative enum values enum NegativeEnum { + NEGATIVE_ENUM_ZERO = 0; FiveBelow = -5; MinusOne = -1; - Zero = 0; } message NegativeEnumMessage { - optional NegativeEnum value = 1; - repeated NegativeEnum values = 2; + NegativeEnum value = 1; + repeated NegativeEnum values = 2 [packed = false]; repeated NegativeEnum packed_values = 3 [packed=true]; } @@ -121,21 +52,22 @@ message DeprecatedChild { } enum DeprecatedEnum { + DEPRECATED_ZERO = 0; one = 1; } message DeprecatedFieldsMessage { - optional int32 PrimitiveValue = 1 [deprecated = true]; + int32 PrimitiveValue = 1 [deprecated = true]; repeated int32 PrimitiveArray = 2 [deprecated = true]; - optional DeprecatedChild MessageValue = 3 [deprecated = true]; + DeprecatedChild MessageValue = 3 [deprecated = true]; repeated DeprecatedChild MessageArray = 4 [deprecated = true]; - optional DeprecatedEnum EnumValue = 5 [deprecated = true]; + DeprecatedEnum EnumValue = 5 [deprecated = true]; repeated DeprecatedEnum EnumArray = 6 [deprecated = true]; } // Issue 45: http://code.google.com/p/protobuf-csharp-port/issues/detail?id=45 message ItemField { - optional int32 item = 1; + int32 item = 1; } diff --git a/csharp/src/ProtocolBuffers.Test/AbstractMessageTest.cs b/csharp/src/ProtocolBuffers.Test/AbstractMessageTest.cs deleted file mode 100644 index 8118808b..00000000 --- a/csharp/src/ProtocolBuffers.Test/AbstractMessageTest.cs +++ /dev/null @@ -1,548 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using System.IO; -using Google.ProtocolBuffers.Descriptors; -using Google.ProtocolBuffers.TestProtos; -using NUnit.Framework; - -namespace Google.ProtocolBuffers -{ - public class AbstractMessageTest - { - [Test] - public void Clear() - { - AbstractMessageWrapper message = - new AbstractMessageWrapper.Builder(TestAllTypes.CreateBuilder(TestUtil.GetAllSet())).Clear().Build(); - TestUtil.AssertClear((TestAllTypes) message.WrappedMessage); - } - - [Test] - public void Copy() - { - AbstractMessageWrapper message = - new AbstractMessageWrapper.Builder(TestAllTypes.CreateBuilder()).MergeFrom(TestUtil.GetAllSet()).Build(); - TestUtil.AssertAllFieldsSet((TestAllTypes) message.WrappedMessage); - } - - [Test] - public void CreateAndBuild() - { - TestAllTypes.CreateBuilder() - .Build(); - } - - [Test] - public void SerializedSize() - { - TestAllTypes message = TestUtil.GetAllSet(); - IMessage abstractMessage = new AbstractMessageWrapper(TestUtil.GetAllSet()); - - Assert.AreEqual(message.SerializedSize, abstractMessage.SerializedSize); - } - - [Test] - public void Serialization() - { - IMessage abstractMessage = new AbstractMessageWrapper(TestUtil.GetAllSet()); - TestUtil.AssertAllFieldsSet(TestAllTypes.ParseFrom(abstractMessage.ToByteString())); - Assert.AreEqual(TestUtil.GetAllSet().ToByteString(), abstractMessage.ToByteString()); - } - - [Test] - public void Parsing() - { - IBuilder builder = new AbstractMessageWrapper.Builder(TestAllTypes.CreateBuilder()); - AbstractMessageWrapper message = - (AbstractMessageWrapper) builder.WeakMergeFrom(TestUtil.GetAllSet().ToByteString()).WeakBuild(); - TestUtil.AssertAllFieldsSet((TestAllTypes) message.WrappedMessage); - } - - [Test] - public void PackedSerialization() - { - IMessage abstractMessage = new AbstractMessageWrapper(TestUtil.GetPackedSet()); - TestUtil.AssertPackedFieldsSet(TestPackedTypes.ParseFrom(abstractMessage.ToByteString())); - Assert.AreEqual(TestUtil.GetPackedSet().ToByteString(), abstractMessage.ToByteString()); - } - - [Test] - public void PackedParsing() - { - AbstractMessageWrapper.Builder builder = new AbstractMessageWrapper.Builder(TestPackedTypes.CreateBuilder()); - AbstractMessageWrapper message = builder.MergeFrom(TestUtil.GetPackedSet().ToByteString()).Build(); - TestUtil.AssertPackedFieldsSet((TestPackedTypes)message.WrappedMessage); - } - - [Test] - public void UnpackedParsingOfPackedInput() - { - byte[] bytes = TestUtil.GetPackedSet().ToByteArray(); - TestUnpackedTypes message = TestUnpackedTypes.ParseFrom(bytes); - TestUtil.AssertUnpackedFieldsSet(message); - } - - [Test] - public void PackedParsingOfUnpackedInput() - { - byte[] bytes = TestUnpackedTypes.ParseFrom(TestUtil.GetPackedSet().ToByteArray()).ToByteArray(); - TestPackedTypes message = TestPackedTypes.ParseFrom(bytes); - TestUtil.AssertPackedFieldsSet(message); - } - - [Test] - public void UnpackedParsingOfPackedInputExtensions() - { - byte[] bytes = TestUtil.GetPackedSet().ToByteArray(); - ExtensionRegistry registry = ExtensionRegistry.CreateInstance(); - Unittest.RegisterAllExtensions(registry); - UnittestImport.RegisterAllExtensions(registry); - TestUnpackedExtensions message = TestUnpackedExtensions.ParseFrom(bytes, registry); - TestUtil.AssertUnpackedExtensionsSet(message); - } - - [Test] - public void PackedParsingOfUnpackedInputExtensions() - { - byte[] bytes = TestUnpackedTypes.ParseFrom(TestUtil.GetPackedSet().ToByteArray()).ToByteArray(); - ExtensionRegistry registry = ExtensionRegistry.CreateInstance(); - Unittest.RegisterAllExtensions(registry); - TestPackedExtensions message = TestPackedExtensions.ParseFrom(bytes, registry); - TestUtil.AssertPackedExtensionsSet(message); - } - - [Test] - public void OptimizedForSize() - { - // We're mostly only Checking that this class was compiled successfully. - TestOptimizedForSize message = TestOptimizedForSize.CreateBuilder().SetI(1).Build(); - message = TestOptimizedForSize.ParseFrom(message.ToByteString()); - Assert.AreEqual(2, message.SerializedSize); - } - - // ----------------------------------------------------------------- - // Tests for isInitialized(). - - private static readonly TestRequired TestRequiredUninitialized = TestRequired.DefaultInstance; - - private static readonly TestRequired TestRequiredInitialized = - TestRequired.CreateBuilder().SetA(1).SetB(2).SetC(3).Build(); - - [Test] - public void IsInitialized() - { - TestRequired.Builder builder = TestRequired.CreateBuilder(); - AbstractMessageWrapper.Builder abstractBuilder = new AbstractMessageWrapper.Builder(builder); - - Assert.IsFalse(abstractBuilder.IsInitialized); - builder.A = 1; - Assert.IsFalse(abstractBuilder.IsInitialized); - builder.B = 1; - Assert.IsFalse(abstractBuilder.IsInitialized); - builder.C = 1; - Assert.IsTrue(abstractBuilder.IsInitialized); - } - - [Test] - public void ForeignIsInitialized() - { - TestRequiredForeign.Builder builder = TestRequiredForeign.CreateBuilder(); - AbstractMessageWrapper.Builder abstractBuilder = new AbstractMessageWrapper.Builder(builder); - - Assert.IsTrue(abstractBuilder.IsInitialized); - - builder.SetOptionalMessage(TestRequiredUninitialized); - Assert.IsFalse(abstractBuilder.IsInitialized); - - builder.SetOptionalMessage(TestRequiredInitialized); - Assert.IsTrue(abstractBuilder.IsInitialized); - - builder.AddRepeatedMessage(TestRequiredUninitialized); - Assert.IsFalse(abstractBuilder.IsInitialized); - - builder.SetRepeatedMessage(0, TestRequiredInitialized); - Assert.IsTrue(abstractBuilder.IsInitialized); - } - - // ----------------------------------------------------------------- - // Tests for mergeFrom - - private static readonly TestAllTypes MergeSource = TestAllTypes.CreateBuilder() - .SetOptionalInt32(1) - .SetOptionalString("foo") - .SetOptionalForeignMessage(ForeignMessage.DefaultInstance) - .AddRepeatedString("bar") - .Build(); - - private static readonly TestAllTypes MergeDest = TestAllTypes.CreateBuilder() - .SetOptionalInt64(2) - .SetOptionalString("baz") - .SetOptionalForeignMessage(ForeignMessage.CreateBuilder().SetC(3).Build()) - .AddRepeatedString("qux") - .Build(); - - private const string MergeResultText = "optional_int32: 1\n" + - "optional_int64: 2\n" + - "optional_string: \"foo\"\n" + - "optional_foreign_message {\n" + - " c: 3\n" + - "}\n" + - "repeated_string: \"qux\"\n" + - "repeated_string: \"bar\"\n"; - - [Test] - public void MergeFrom() - { - AbstractMessageWrapper result = (AbstractMessageWrapper) - new AbstractMessageWrapper.Builder(TestAllTypes.CreateBuilder(MergeDest)) - .MergeFrom(MergeSource) - .Build(); - - Assert.AreEqual(MergeResultText, result.ToString()); - } - - // ----------------------------------------------------------------- - // Tests for equals and hashCode - - [Test] - public void EqualsAndHashCode() - { - TestAllTypes a = TestUtil.GetAllSet(); - TestAllTypes b = TestAllTypes.CreateBuilder().Build(); - TestAllTypes c = TestAllTypes.CreateBuilder(b).AddRepeatedString("x").Build(); - TestAllTypes d = TestAllTypes.CreateBuilder(c).AddRepeatedString("y").Build(); - TestAllExtensions e = TestUtil.GetAllExtensionsSet(); - TestAllExtensions f = TestAllExtensions.CreateBuilder(e) - .AddExtension(Unittest.RepeatedInt32Extension, 999).Build(); - - CheckEqualsIsConsistent(a); - CheckEqualsIsConsistent(b); - CheckEqualsIsConsistent(c); - CheckEqualsIsConsistent(d); - CheckEqualsIsConsistent(e); - CheckEqualsIsConsistent(f); - - CheckNotEqual(a, b); - CheckNotEqual(a, c); - CheckNotEqual(a, d); - CheckNotEqual(a, e); - CheckNotEqual(a, f); - - CheckNotEqual(b, c); - CheckNotEqual(b, d); - CheckNotEqual(b, e); - CheckNotEqual(b, f); - - CheckNotEqual(c, d); - CheckNotEqual(c, e); - CheckNotEqual(c, f); - - CheckNotEqual(d, e); - CheckNotEqual(d, f); - - CheckNotEqual(e, f); - - // Deserializing into the TestEmptyMessage such that every field is an UnknownFieldSet.Field - TestEmptyMessage eUnknownFields = TestEmptyMessage.ParseFrom(e.ToByteArray()); - TestEmptyMessage fUnknownFields = TestEmptyMessage.ParseFrom(f.ToByteArray()); - CheckNotEqual(eUnknownFields, fUnknownFields); - CheckEqualsIsConsistent(eUnknownFields); - CheckEqualsIsConsistent(fUnknownFields); - - // Subseqent reconstitutions should be identical - TestEmptyMessage eUnknownFields2 = TestEmptyMessage.ParseFrom(e.ToByteArray()); - CheckEqualsIsConsistent(eUnknownFields, eUnknownFields2); - } - - /// - /// Asserts that the given protos are equal and have the same hash code. - /// - private static void CheckEqualsIsConsistent(IMessage message) - { - // Object should be equal to itself. - Assert.AreEqual(message, message); - - // Object should be equal to a dynamic copy of itself. - DynamicMessage dynamic = DynamicMessage.CreateBuilder(message).Build(); - CheckEqualsIsConsistent(message, dynamic); - } - - /// - /// Asserts that the given protos are equal and have the same hash code. - /// - private static void CheckEqualsIsConsistent(IMessage message1, IMessage message2) - { - // Not using Assert.AreEqual as that checks for type equality, which isn't - // what we want bearing in mind the dynamic message checks. - Assert.IsTrue(message1.Equals(message2)); - Assert.IsTrue(message2.Equals(message1)); - Assert.AreEqual(message2.GetHashCode(), message1.GetHashCode()); - } - - /// - /// Asserts that the given protos are not equal and have different hash codes. - /// - /// - /// It's valid for non-equal objects to have the same hash code, so - /// this test is stricter than it needs to be. However, this should happen - /// relatively rarely. (If this test fails, it's probably still due to a bug.) - /// - private static void CheckNotEqual(IMessage m1, IMessage m2) - { - String equalsError = string.Format("{0} should not be equal to {1}", m1, m2); - Assert.IsFalse(m1.Equals(m2), equalsError); - Assert.IsFalse(m2.Equals(m1), equalsError); - - Assert.IsFalse(m1.GetHashCode() == m2.GetHashCode(), - string.Format("{0} should have a different hash code from {1}", m1, m2)); - } - - /// - /// Extends AbstractMessage and wraps some other message object. The methods - /// of the Message interface which aren't explicitly implemented by - /// AbstractMessage are forwarded to the wrapped object. This allows us to - /// test that AbstractMessage's implementations work even if the wrapped - /// object does not use them. - /// - private class AbstractMessageWrapper : AbstractMessage - { - private readonly IMessage wrappedMessage; - - public IMessage WrappedMessage - { - get { return wrappedMessage; } - } - - public AbstractMessageWrapper(IMessage wrappedMessage) - { - this.wrappedMessage = wrappedMessage; - } - - public override MessageDescriptor DescriptorForType - { - get { return wrappedMessage.DescriptorForType; } - } - - public override AbstractMessageWrapper DefaultInstanceForType - { - get { return new AbstractMessageWrapper(wrappedMessage.WeakDefaultInstanceForType); } - } - - public override IDictionary AllFields - { - get { return wrappedMessage.AllFields; } - } - - public override bool HasField(FieldDescriptor field) - { - return wrappedMessage.HasField(field); - } - - public override bool HasOneof(OneofDescriptor oneof) - { - return wrappedMessage.HasOneof(oneof); - } - - public override FieldDescriptor OneofFieldDescriptor(OneofDescriptor oneof) - { - return wrappedMessage.OneofFieldDescriptor(oneof); - } - - public override object this[FieldDescriptor field] - { - get { return wrappedMessage[field]; } - } - - public override object this[FieldDescriptor field, int index] - { - get { return wrappedMessage[field, index]; } - } - - public override int GetRepeatedFieldCount(FieldDescriptor field) - { - return wrappedMessage.GetRepeatedFieldCount(field); - } - - public override UnknownFieldSet UnknownFields - { - get { return wrappedMessage.UnknownFields; } - } - - public override Builder CreateBuilderForType() - { - return new Builder(wrappedMessage.WeakCreateBuilderForType()); - } - - public override Builder ToBuilder() - { - return new Builder(wrappedMessage.WeakToBuilder()); - } - - internal class Builder : AbstractBuilder - { - private readonly IBuilder wrappedBuilder; - - protected override Builder ThisBuilder - { - get { return this; } - } - - internal Builder(IBuilder wrappedBuilder) - { - this.wrappedBuilder = wrappedBuilder; - } - - public override Builder MergeFrom(AbstractMessageWrapper other) - { - wrappedBuilder.WeakMergeFrom(other.wrappedMessage); - return this; - } - - public override bool IsInitialized - { - get { return wrappedBuilder.IsInitialized; } - } - - public override IDictionary AllFields - { - get { return wrappedBuilder.AllFields; } - } - - public override object this[FieldDescriptor field] - { - get { return wrappedBuilder[field]; } - set { wrappedBuilder[field] = value; } - } - - public override MessageDescriptor DescriptorForType - { - get { return wrappedBuilder.DescriptorForType; } - } - - public override int GetRepeatedFieldCount(FieldDescriptor field) - { - return wrappedBuilder.GetRepeatedFieldCount(field); - } - - public override object this[FieldDescriptor field, int index] - { - get { return wrappedBuilder[field, index]; } - set { wrappedBuilder[field, index] = value; } - } - - public override bool HasField(FieldDescriptor field) - { - return wrappedBuilder.HasField(field); - } - - public override bool HasOneof(OneofDescriptor oneof) - { - return wrappedBuilder.HasOneof(oneof); - } - - public override FieldDescriptor OneofFieldDescriptor(OneofDescriptor oneof) - { - return wrappedBuilder.OneofFieldDescriptor(oneof); - } - - public override UnknownFieldSet UnknownFields - { - get { return wrappedBuilder.UnknownFields; } - set { wrappedBuilder.UnknownFields = value; } - } - - public override AbstractMessageWrapper Build() - { - return new AbstractMessageWrapper(wrappedBuilder.WeakBuild()); - } - - public override AbstractMessageWrapper BuildPartial() - { - return new AbstractMessageWrapper(wrappedBuilder.WeakBuildPartial()); - } - - public override Builder Clone() - { - return new Builder(wrappedBuilder.WeakClone()); - } - - public override AbstractMessageWrapper DefaultInstanceForType - { - get { return new AbstractMessageWrapper(wrappedBuilder.WeakDefaultInstanceForType); } - } - - public override Builder ClearField(FieldDescriptor field) - { - wrappedBuilder.WeakClearField(field); - return this; - } - - public override Builder ClearOneof(OneofDescriptor oneof) - { - wrappedBuilder.WeakClearOneof(oneof); - return this; - } - - public override Builder AddRepeatedField(FieldDescriptor field, object value) - { - wrappedBuilder.WeakAddRepeatedField(field, value); - return this; - } - - public override IBuilder CreateBuilderForField(FieldDescriptor field) - { - wrappedBuilder.CreateBuilderForField(field); - return this; - } - - public override Builder MergeFrom(IMessage other) - { - wrappedBuilder.WeakMergeFrom(other); - return this; - } - - public override Builder MergeFrom(ICodedInputStream input, ExtensionRegistry extensionRegistry) - { - wrappedBuilder.WeakMergeFrom(input, extensionRegistry); - return this; - } - } - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers.Test/ByteStringTest.cs b/csharp/src/ProtocolBuffers.Test/ByteStringTest.cs index e4f7bd9e..0edd149b 100644 --- a/csharp/src/ProtocolBuffers.Test/ByteStringTest.cs +++ b/csharp/src/ProtocolBuffers.Test/ByteStringTest.cs @@ -38,7 +38,7 @@ using System; using System.Text; using NUnit.Framework; -namespace Google.ProtocolBuffers +namespace Google.Protobuf { public class ByteStringTest { diff --git a/csharp/src/ProtocolBuffers.Test/CodedInputStreamTest.cs b/csharp/src/ProtocolBuffers.Test/CodedInputStreamTest.cs index 9bb8ba27..57650049 100644 --- a/csharp/src/ProtocolBuffers.Test/CodedInputStreamTest.cs +++ b/csharp/src/ProtocolBuffers.Test/CodedInputStreamTest.cs @@ -37,11 +37,12 @@ using System; using System.Collections.Generic; using System.IO; -using Google.ProtocolBuffers.Descriptors; -using Google.ProtocolBuffers.TestProtos; +using Google.Protobuf.Collections; +using Google.Protobuf.Descriptors; +using Google.Protobuf.TestProtos; using NUnit.Framework; -namespace Google.ProtocolBuffers +namespace Google.Protobuf { public class CodedInputStreamTest { @@ -231,7 +232,7 @@ namespace Google.ProtocolBuffers Assert.AreEqual(0x7FFFFFFFFFFFFFFFL, CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFEL)); Assert.AreEqual(unchecked((long) 0x8000000000000000L), CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFFL)); } - + /* [Test] public void ReadWholeMessage() { @@ -273,7 +274,7 @@ namespace Google.ProtocolBuffers unknownFields.MergeFieldFrom(tag, input1); input2.SkipField(); } - } + }*/ /// /// Test that a bug in SkipRawBytes has been fixed: if the skip @@ -290,7 +291,7 @@ namespace Google.ProtocolBuffers input.PopLimit(limit); Assert.AreEqual(2, input.ReadRawByte()); } - + /* public void ReadHugeBlob() { // Allocate and initialize a 1MB blob. @@ -318,7 +319,7 @@ namespace Google.ProtocolBuffers .SetOptionalBytes(TestUtil.GetAllSet().OptionalBytes) .Build(); TestUtil.AssertAllFieldsSet(message3); - } + }*/ [Test] public void ReadMaliciouslyLargeBlob() @@ -348,12 +349,11 @@ namespace Google.ProtocolBuffers { if (depth == 0) { - return TestRecursiveMessage.CreateBuilder().SetI(5).Build(); + return new TestRecursiveMessage { I = 5 }; } else { - return TestRecursiveMessage.CreateBuilder() - .SetA(MakeRecursiveMessage(depth - 1)).Build(); + return new TestRecursiveMessage { A = MakeRecursiveMessage(depth - 1) }; } } @@ -361,12 +361,12 @@ namespace Google.ProtocolBuffers { if (depth == 0) { - Assert.IsFalse(message.HasA); + Assert.IsNull(message.A); Assert.AreEqual(5, message.I); } else { - Assert.IsTrue(message.HasA); + Assert.IsNotNull(message.A); AssertMessageDepth(message.A, depth - 1); } } @@ -377,15 +377,16 @@ namespace Google.ProtocolBuffers ByteString data64 = MakeRecursiveMessage(64).ToByteString(); ByteString data65 = MakeRecursiveMessage(65).ToByteString(); - AssertMessageDepth(TestRecursiveMessage.ParseFrom(data64), 64); + AssertMessageDepth(TestRecursiveMessage.Parser.ParseFrom(data64), 64); - Assert.Throws(() => TestRecursiveMessage.ParseFrom(data65)); + Assert.Throws(() => TestRecursiveMessage.Parser.ParseFrom(data65)); CodedInputStream input = data64.CreateCodedInput(); input.SetRecursionLimit(8); - Assert.Throws(() => TestRecursiveMessage.ParseFrom(input)); + Assert.Throws(() => TestRecursiveMessage.Parser.ParseFrom(input)); } + /* [Test] public void SizeLimit() { @@ -396,7 +397,7 @@ namespace Google.ProtocolBuffers input.SetSizeLimit(16); Assert.Throws(() => TestAllTypes.ParseFrom(input)); - } + }*/ [Test] public void ResetSizeCounter() @@ -465,17 +466,16 @@ namespace Google.ProtocolBuffers } } - enum TestNegEnum { None = 0, Value = -2 } + enum TestNegEnum : long { None = 0, Value = -2 } [Test] public void TestNegativeEnum() { byte[] bytes = new byte[10] { 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01 }; CodedInputStream input = CodedInputStream.CreateInstance(bytes); - object unk; TestNegEnum val = TestNegEnum.None; - Assert.IsTrue(input.ReadEnum(ref val, out unk)); + Assert.IsTrue(input.ReadEnum(ref val)); Assert.IsTrue(input.IsAtEnd); Assert.AreEqual(TestNegEnum.Value, val); } @@ -487,7 +487,7 @@ namespace Google.ProtocolBuffers int msgSize = 1 + 1 + arraySize; byte[] bytes = new byte[msgSize]; CodedOutputStream output = CodedOutputStream.CreateInstance(bytes); - output.WritePackedInt32Array(8, "", arraySize, new int[] { 0, -1, -2, -3, -4, -5 }); + output.WritePackedInt32Array(8, "", new RepeatedField { 0, -1, -2, -3, -4, -5 }); Assert.AreEqual(0, output.SpaceLeft); @@ -497,15 +497,12 @@ namespace Google.ProtocolBuffers Assert.IsTrue(input.ReadTag(out tag, out name)); List values = new List(); - ICollection unk; - input.ReadEnumArray(tag, name, values, out unk); + input.ReadEnumArray(tag, name, values); - Assert.AreEqual(2, values.Count); + Assert.AreEqual(6, values.Count); Assert.AreEqual(TestNegEnum.None, values[0]); - Assert.AreEqual(TestNegEnum.Value, values[1]); - - Assert.NotNull(unk); - Assert.AreEqual(4, unk.Count); + Assert.AreEqual(TestNegEnum.Value, values[2]); + // TODO(jonskeet): Test unknown value preservation } [Test] @@ -515,7 +512,7 @@ namespace Google.ProtocolBuffers int msgSize = arraySize; byte[] bytes = new byte[msgSize]; CodedOutputStream output = CodedOutputStream.CreateInstance(bytes); - output.WriteInt32Array(8, "", new int[] { 0, -1, -2, -3, -4, -5 }); + output.WriteInt32Array(8, "", new RepeatedField { 0, -1, -2, -3, -4, -5 }); Assert.AreEqual(0, output.SpaceLeft); @@ -525,15 +522,12 @@ namespace Google.ProtocolBuffers Assert.IsTrue(input.ReadTag(out tag, out name)); List values = new List(); - ICollection unk; - input.ReadEnumArray(tag, name, values, out unk); + input.ReadEnumArray(tag, name, values); - Assert.AreEqual(2, values.Count); + Assert.AreEqual(6, values.Count); Assert.AreEqual(TestNegEnum.None, values[0]); - Assert.AreEqual(TestNegEnum.Value, values[1]); - - Assert.NotNull(unk); - Assert.AreEqual(4, unk.Count); + Assert.AreEqual(TestNegEnum.Value, values[2]); + // TODO(jonskeet): Test unknown value preservation } //Issue 71: CodedInputStream.ReadBytes go to slow path unnecessarily diff --git a/csharp/src/ProtocolBuffers.Test/CodedOutputStreamTest.cs b/csharp/src/ProtocolBuffers.Test/CodedOutputStreamTest.cs index 4d5b8302..df80b3af 100644 --- a/csharp/src/ProtocolBuffers.Test/CodedOutputStreamTest.cs +++ b/csharp/src/ProtocolBuffers.Test/CodedOutputStreamTest.cs @@ -37,10 +37,10 @@ using System; using System.Collections.Generic; using System.IO; -using Google.ProtocolBuffers.TestProtos; +using Google.Protobuf.Collections; using NUnit.Framework; -namespace Google.ProtocolBuffers +namespace Google.Protobuf { public class CodedOutputStreamTest { @@ -195,6 +195,7 @@ namespace Google.ProtocolBuffers 0x9abcdef012345678UL); } + /* [Test] public void WriteWholeMessage() { @@ -228,6 +229,7 @@ namespace Google.ProtocolBuffers TestUtil.AssertEqualBytes(TestUtil.GetGoldenPackedFieldsMessage().ToByteArray(), rawBytes); } + */ [Test] public void EncodeZigZag32() @@ -294,25 +296,27 @@ namespace Google.ProtocolBuffers public void TestNegativeEnumNoTag() { Assert.AreEqual(10, CodedOutputStream.ComputeInt32SizeNoTag(-2)); - Assert.AreEqual(10, CodedOutputStream.ComputeEnumSizeNoTag(-2)); + Assert.AreEqual(10, CodedOutputStream.ComputeEnumSizeNoTag(TestNegEnum.Value)); byte[] bytes = new byte[10]; CodedOutputStream output = CodedOutputStream.CreateInstance(bytes); - output.WriteEnumNoTag(-2); + output.WriteEnumNoTag(TestNegEnum.Value); Assert.AreEqual(0, output.SpaceLeft); Assert.AreEqual("FE-FF-FF-FF-FF-FF-FF-FF-FF-01", BitConverter.ToString(bytes)); } + enum TestNegEnum : long { None = 0, Value = -2 } + [Test] public void TestNegativeEnumWithTag() { Assert.AreEqual(11, CodedOutputStream.ComputeInt32Size(8, -2)); - Assert.AreEqual(11, CodedOutputStream.ComputeEnumSize(8, -2)); + Assert.AreEqual(11, CodedOutputStream.ComputeEnumSize(8, TestNegEnum.Value)); byte[] bytes = new byte[11]; CodedOutputStream output = CodedOutputStream.CreateInstance(bytes); - output.WriteEnum(8, "", -2, -2); + output.WriteEnum(8, "", TestNegEnum.Value); Assert.AreEqual(0, output.SpaceLeft); //fyi, 0x40 == 0x08 << 3 + 0, field num + wire format shift @@ -326,7 +330,8 @@ namespace Google.ProtocolBuffers int msgSize = 1 + 1 + arraySize; byte[] bytes = new byte[msgSize]; CodedOutputStream output = CodedOutputStream.CreateInstance(bytes); - output.WritePackedEnumArray(8, "", arraySize, new int[] { 0, -1, -2, -3, -4, -5 }); + output.WritePackedEnumArray(8, "", new RepeatedField { + 0, (TestNegEnum) (-1), TestNegEnum.Value, (TestNegEnum) (-3), (TestNegEnum) (-4), (TestNegEnum) (-5) }); Assert.AreEqual(0, output.SpaceLeft); @@ -350,8 +355,8 @@ namespace Google.ProtocolBuffers int msgSize = arraySize; byte[] bytes = new byte[msgSize]; CodedOutputStream output = CodedOutputStream.CreateInstance(bytes); - output.WriteEnumArray(8, "", new int[] { 0, -1, -2, -3, -4, -5 }); - + output.WriteEnumArray(8, "", new RepeatedField { + 0, (TestNegEnum) (-1), TestNegEnum.Value, (TestNegEnum) (-3), (TestNegEnum) (-4), (TestNegEnum) (-5) }); Assert.AreEqual(0, output.SpaceLeft); CodedInputStream input = CodedInputStream.CreateInstance(bytes); diff --git a/csharp/src/ProtocolBuffers.Test/Collections/PopsicleListTest.cs b/csharp/src/ProtocolBuffers.Test/Collections/PopsicleListTest.cs deleted file mode 100644 index f336a84b..00000000 --- a/csharp/src/ProtocolBuffers.Test/Collections/PopsicleListTest.cs +++ /dev/null @@ -1,125 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using NUnit.Framework; - -namespace Google.ProtocolBuffers.Collections -{ - public class PopsicleListTest - { - [Test] - public void MutatingOperationsOnFrozenList() - { - PopsicleList list = new PopsicleList(); - list.MakeReadOnly(); - Assert.Throws(() => list.Add("")); - Assert.Throws(() => list.Clear()); - Assert.Throws(() => list.Insert(0, "")); - Assert.Throws(() => list.Remove("")); - Assert.Throws(() => list.RemoveAt(0)); - Assert.Throws(() => list.Add(new[] { "", "" })); - } - - [Test] - public void NonMutatingOperationsOnFrozenList() - { - PopsicleList list = new PopsicleList(); - list.MakeReadOnly(); - Assert.IsFalse(list.Contains("")); - Assert.AreEqual(0, list.Count); - list.CopyTo(new string[5], 0); - list.GetEnumerator(); - Assert.AreEqual(-1, list.IndexOf("")); - Assert.IsTrue(list.IsReadOnly); - } - - [Test] - public void MutatingOperationsOnFluidList() - { - PopsicleList list = new PopsicleList(); - list.Add(""); - list.Clear(); - list.Insert(0, ""); - list.Remove(""); - list.Add("x"); // Just to make the next call valid - list.RemoveAt(0); - } - - [Test] - public void NonMutatingOperationsOnFluidList() - { - PopsicleList list = new PopsicleList(); - Assert.IsFalse(list.Contains("")); - Assert.AreEqual(0, list.Count); - list.CopyTo(new string[5], 0); - list.GetEnumerator(); - Assert.AreEqual(-1, list.IndexOf("")); - Assert.IsFalse(list.IsReadOnly); - } - - [Test] - public void DoesNotAddNullEnumerable() - { - PopsicleList list = new PopsicleList(); - Assert.Throws(() => list.Add((IEnumerable) null)); - } - - [Test] - public void DoesNotAddRangeWithNull() - { - PopsicleList list = new PopsicleList(); - // TODO(jonskeet): Change to ArgumentException? The argument isn't null... - Assert.Throws(() => list.Add(new[] {"a", "b", null})); - } - - [Test] - public void DoesNotAddNull() - { - PopsicleList list = new PopsicleList(); - Assert.Throws(() => list.Add((string) null)); - } - - [Test] - public void DoesNotSetNull() - { - PopsicleList list = new PopsicleList(); - list.Add("a"); - Assert.Throws(() => list[0] = null); - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers.Test/Compatibility/BinaryCompatibilityTests.cs b/csharp/src/ProtocolBuffers.Test/Compatibility/BinaryCompatibilityTests.cs deleted file mode 100644 index 30d257ad..00000000 --- a/csharp/src/ProtocolBuffers.Test/Compatibility/BinaryCompatibilityTests.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; - -namespace Google.ProtocolBuffers.Compatibility -{ - public class BinaryCompatibilityTests : CompatibilityTests - { - protected override object SerializeMessage(TMessage message) - { - byte[] bresult = message.ToByteArray(); - return Convert.ToBase64String(bresult); - } - - protected override TBuilder DeserializeMessage(object message, TBuilder builder, ExtensionRegistry registry) - { - return builder.MergeFrom((byte[])Convert.FromBase64String((string)message), registry); - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers.Test/Compatibility/CompatibilityTests.cs b/csharp/src/ProtocolBuffers.Test/Compatibility/CompatibilityTests.cs deleted file mode 100644 index a050827e..00000000 --- a/csharp/src/ProtocolBuffers.Test/Compatibility/CompatibilityTests.cs +++ /dev/null @@ -1,227 +0,0 @@ -using System; -using Google.ProtocolBuffers.TestProtos; -using NUnit.Framework; - - -namespace Google.ProtocolBuffers.Compatibility -{ - /// - /// This abstract base implements several tests to ensure that well-known messages can be written - /// and read to/from various formats without losing data. Implementations override the two serialization - /// methods to provide the tests with the means to read and write for a given format. - /// - public abstract class CompatibilityTests - { - protected abstract object SerializeMessage(TMessage message) - where TMessage : IMessageLite - where TBuilder : IBuilderLite; - - protected abstract TBuilder DeserializeMessage(object message, TBuilder builder, ExtensionRegistry registry) - where TMessage : IMessageLite - where TBuilder : IBuilderLite; - - protected virtual void AssertOutputEquals(object lhs, object rhs) - { - Assert.AreEqual(lhs, rhs); - } - - [Test] - public virtual void RoundTripWithEmptyChildMessageSize() - { - SizeMessage1 msg = SizeMessage1.CreateBuilder() - .SetField100(100) - .SetField15(SizeMessage1SubMessage.DefaultInstance) - .BuildPartial(); - byte[] contents = msg.ToByteArray(); - object content = SerializeMessage(msg); - - SizeMessage1 copy = DeserializeMessage(content, SizeMessage1.CreateBuilder(), ExtensionRegistry.Empty).BuildPartial(); - - Assert.AreEqual(msg, copy); - AssertOutputEquals(content, SerializeMessage(copy)); - Assert.AreEqual(Convert.ToBase64String(contents), Convert.ToBase64String(copy.ToByteArray())); - } - - [Test] - public virtual void RoundTripWithEmptyChildMessageSpeed() - { - SpeedMessage1 msg = SpeedMessage1.CreateBuilder() - .SetField100(100) - .SetField15(SpeedMessage1SubMessage.DefaultInstance) - .BuildPartial(); - byte[] contents = msg.ToByteArray(); - object content = SerializeMessage(msg); - - SpeedMessage1 copy = DeserializeMessage(content, SpeedMessage1.CreateBuilder(), ExtensionRegistry.Empty).BuildPartial(); - - Assert.AreEqual(msg, copy); - AssertOutputEquals(content, SerializeMessage(copy)); - Assert.AreEqual(Convert.ToBase64String(contents), Convert.ToBase64String(copy.ToByteArray())); - } - - [Test] - public virtual void RoundTripMessage1OptimizeSize() - { - SizeMessage1 msg = SizeMessage1.CreateBuilder().MergeFrom(TestResources.google_message1).Build(); - object content = SerializeMessage(msg); - - SizeMessage1 copy = DeserializeMessage(content, SizeMessage1.CreateBuilder(), ExtensionRegistry.Empty).Build(); - - Assert.AreEqual(msg, copy); - AssertOutputEquals(content, SerializeMessage(copy)); - Assert.AreEqual(Convert.ToBase64String(TestResources.google_message1), Convert.ToBase64String(copy.ToByteArray())); - } - - [Test] - public virtual void RoundTripMessage2OptimizeSize() - { - SizeMessage2 msg = SizeMessage2.CreateBuilder().MergeFrom(TestResources.google_message2).Build(); - object content = SerializeMessage(msg); - - SizeMessage2 copy = DeserializeMessage(content, SizeMessage2.CreateBuilder(), ExtensionRegistry.Empty).Build(); - - Assert.AreEqual(msg, copy); - AssertOutputEquals(content, SerializeMessage(copy)); - Assert.AreEqual(Convert.ToBase64String(TestResources.google_message2), Convert.ToBase64String(copy.ToByteArray())); - } - - [Test] - public virtual void RoundTripMessage1OptimizeSpeed() - { - SpeedMessage1 msg = SpeedMessage1.CreateBuilder().MergeFrom(TestResources.google_message1).Build(); - object content = SerializeMessage(msg); - - SpeedMessage1 copy = DeserializeMessage(content, SpeedMessage1.CreateBuilder(), ExtensionRegistry.Empty).Build(); - - Assert.AreEqual(msg, copy); - AssertOutputEquals(content, SerializeMessage(copy)); - Assert.AreEqual(Convert.ToBase64String(TestResources.google_message1), Convert.ToBase64String(copy.ToByteArray())); - } - - [Test] - public virtual void RoundTripMessage2OptimizeSpeed() - { - SpeedMessage2 msg = SpeedMessage2.CreateBuilder().MergeFrom(TestResources.google_message2).Build(); - object content = SerializeMessage(msg); - - SpeedMessage2 copy = DeserializeMessage(content, SpeedMessage2.CreateBuilder(), ExtensionRegistry.Empty).Build(); - - Assert.AreEqual(msg, copy); - AssertOutputEquals(content, SerializeMessage(copy)); - Assert.AreEqual(Convert.ToBase64String(TestResources.google_message2), Convert.ToBase64String(copy.ToByteArray())); - } - - #region Test message builders - - protected static TestAllTypes.Builder AddAllTypes(TestAllTypes.Builder builder) - { - return builder.SetOptionalInt32(1001) - .SetOptionalInt64(1001) - .SetOptionalUint32(1001) - .SetOptionalUint64(1001) - .SetOptionalSint32(-1001) - .SetOptionalSint64(-1001) - .SetOptionalFixed32(1001) - .SetOptionalFixed64(1001) - .SetOptionalSfixed32(-1001) - .SetOptionalSfixed64(-1001) - .SetOptionalFloat(1001.1001f) - .SetOptionalDouble(1001.1001) - .SetOptionalBool(true) - .SetOptionalString("this is a string value") - .SetOptionalBytes(ByteString.CopyFromUtf8("this is an array of bytes")) - .SetOptionalGroup(new TestAllTypes.Types.OptionalGroup.Builder().SetA(1001)) - .SetOptionalNestedMessage(new TestAllTypes.Types.NestedMessage.Builder().SetBb(1001)) - .SetOptionalNestedEnum(TestAllTypes.Types.NestedEnum.FOO) - ; - } - - protected static TestAllTypes.Builder AddRepeatedTypes(TestAllTypes.Builder builder, int size) - { - //repeated values - for (int i = 0; i < size; i++) - builder.AddRepeatedInt32(1001 + i) - .AddRepeatedInt64(1001) - .AddRepeatedUint32(1001) - .AddRepeatedUint64(1001) - .AddRepeatedSint32(-1001) - .AddRepeatedSint64(-1001) - .AddRepeatedFixed32(1001) - .AddRepeatedFixed64(1001) - .AddRepeatedSfixed32(-1001) - .AddRepeatedSfixed64(-1001) - .AddRepeatedFloat(1001.1001f) - .AddRepeatedDouble(1001.1001) - .AddRepeatedBool(true) - .AddRepeatedString("this is a string value") - .AddRepeatedBytes(ByteString.CopyFromUtf8("this is an array of bytes")) - .AddRepeatedGroup(new TestAllTypes.Types.RepeatedGroup.Builder().SetA(1001)) - .AddRepeatedNestedMessage(new TestAllTypes.Types.NestedMessage.Builder().SetBb(1001)) - .AddRepeatedNestedEnum(TestAllTypes.Types.NestedEnum.FOO) - ; - return builder; - } - - protected static TestPackedTypes.Builder AddPackedTypes(TestPackedTypes.Builder builder, int size) - { - for(int i=0; i < size; i++ ) - builder.AddPackedInt32(1001) - .AddPackedInt64(1001) - .AddPackedUint32(1001) - .AddPackedUint64(1001) - .AddPackedSint32(-1001) - .AddPackedSint64(-1001) - .AddPackedFixed32(1001) - .AddPackedFixed64(1001) - .AddPackedSfixed32(-1001) - .AddPackedSfixed64(-1001) - .AddPackedFloat(1001.1001f) - .AddPackedDouble(1001.1001) - .AddPackedBool(true) - .AddPackedEnum(ForeignEnum.FOREIGN_FOO) - ; - return builder; - } - - #endregion - - [Test] - public void TestRoundTripAllTypes() - { - TestAllTypes msg = AddAllTypes(new TestAllTypes.Builder()).Build(); - object content = SerializeMessage(msg); - - TestAllTypes copy = DeserializeMessage(content, TestAllTypes.CreateBuilder(), ExtensionRegistry.Empty).Build(); - - Assert.AreEqual(msg, copy); - AssertOutputEquals(content, SerializeMessage(copy)); - Assert.AreEqual(Convert.ToBase64String(msg.ToByteArray()), Convert.ToBase64String(copy.ToByteArray())); - } - - [Test] - public void TestRoundTripRepeatedTypes() - { - TestAllTypes msg = AddRepeatedTypes(new TestAllTypes.Builder(), 5).Build(); - object content = SerializeMessage(msg); - - TestAllTypes copy = DeserializeMessage(content, TestAllTypes.CreateBuilder(), ExtensionRegistry.Empty).Build(); - - Assert.AreEqual(msg, copy); - AssertOutputEquals(content, SerializeMessage(copy)); - Assert.AreEqual(Convert.ToBase64String(msg.ToByteArray()), Convert.ToBase64String(copy.ToByteArray())); - } - - [Test] - public void TestRoundTripPackedTypes() - { - TestPackedTypes msg = AddPackedTypes(new TestPackedTypes.Builder(), 5).Build(); - object content = SerializeMessage(msg); - - TestPackedTypes copy = DeserializeMessage(content, TestPackedTypes.CreateBuilder(), ExtensionRegistry.Empty).Build(); - - Assert.AreEqual(msg, copy); - AssertOutputEquals(content, SerializeMessage(copy)); - Assert.AreEqual(Convert.ToBase64String(msg.ToByteArray()), Convert.ToBase64String(copy.ToByteArray())); - } - } -} diff --git a/csharp/src/ProtocolBuffers.Test/Compatibility/DictionaryCompatibilityTests.cs b/csharp/src/ProtocolBuffers.Test/Compatibility/DictionaryCompatibilityTests.cs deleted file mode 100644 index 299bb1a6..00000000 --- a/csharp/src/ProtocolBuffers.Test/Compatibility/DictionaryCompatibilityTests.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System; -using System.Collections.Generic; -using Google.ProtocolBuffers.Serialization; -using NUnit.Framework; - -namespace Google.ProtocolBuffers.Compatibility -{ - [TestFixture] - public class DictionaryCompatibilityTests : CompatibilityTests - { - protected override object SerializeMessage(TMessage message) - { - DictionaryWriter writer = new DictionaryWriter(); - writer.WriteMessage(message); - return writer.ToDictionary(); - } - - protected override TBuilder DeserializeMessage(object message, TBuilder builder, ExtensionRegistry registry) - { - new DictionaryReader((IDictionary)message).Merge(builder); - return builder; - } - - protected override void AssertOutputEquals(object lhs, object rhs) - { - IDictionary left = (IDictionary)lhs; - IDictionary right = (IDictionary)rhs; - - Assert.AreEqual( - String.Join(",", new List(left.Keys).ToArray()), - String.Join(",", new List(right.Keys).ToArray()) - ); - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers.Test/Compatibility/JsonCompatibilityTests.cs b/csharp/src/ProtocolBuffers.Test/Compatibility/JsonCompatibilityTests.cs deleted file mode 100644 index a1e0ed33..00000000 --- a/csharp/src/ProtocolBuffers.Test/Compatibility/JsonCompatibilityTests.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System.IO; -using Google.ProtocolBuffers.Serialization; -using NUnit.Framework; - -namespace Google.ProtocolBuffers.Compatibility -{ - [TestFixture] - public class JsonCompatibilityTests : CompatibilityTests - { - protected override object SerializeMessage(TMessage message) - { - StringWriter sw = new StringWriter(); - JsonFormatWriter.CreateInstance(sw) - .WriteMessage(message); - return sw.ToString(); - } - - protected override TBuilder DeserializeMessage(object message, TBuilder builder, ExtensionRegistry registry) - { - JsonFormatReader.CreateInstance((string)message).Merge(builder); - return builder; - } - } - - [TestFixture] - public class JsonCompatibilityFormattedTests : CompatibilityTests - { - protected override object SerializeMessage(TMessage message) - { - StringWriter sw = new StringWriter(); - JsonFormatWriter.CreateInstance(sw) - .Formatted() - .WriteMessage(message); - return sw.ToString(); - } - - protected override TBuilder DeserializeMessage(object message, TBuilder builder, ExtensionRegistry registry) - { - JsonFormatReader.CreateInstance((string)message).Merge(builder); - return builder; - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers.Test/Compatibility/TestResources.cs b/csharp/src/ProtocolBuffers.Test/Compatibility/TestResources.cs deleted file mode 100644 index 2282d61f..00000000 --- a/csharp/src/ProtocolBuffers.Test/Compatibility/TestResources.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System.IO; -using NUnit.Framework; - -namespace Google.ProtocolBuffers.Compatibility -{ - static class TestResources - { - public static byte[] google_message1 - { - get - { - Stream resource = typeof(TestResources).Assembly.GetManifestResourceStream( - typeof(TestResources).Namespace + ".google_message1.dat"); - - Assert.NotNull(resource); - - byte[] bytes = new byte[resource.Length]; - int amtRead = resource.Read(bytes, 0, bytes.Length); - Assert.AreEqual(bytes.Length, amtRead); - return bytes; - } - } - public static byte[] google_message2 - { - get - { - Stream resource = typeof(TestResources).Assembly.GetManifestResourceStream( - typeof(TestResources).Namespace + ".google_message2.dat"); - - Assert.NotNull(resource); - byte[] bytes = new byte[resource.Length]; - int amtRead = resource.Read(bytes, 0, bytes.Length); - Assert.AreEqual(bytes.Length, amtRead); - return bytes; - } - } - } -} diff --git a/csharp/src/ProtocolBuffers.Test/Compatibility/TextCompatibilityTests.cs b/csharp/src/ProtocolBuffers.Test/Compatibility/TextCompatibilityTests.cs deleted file mode 100644 index 89d6e260..00000000 --- a/csharp/src/ProtocolBuffers.Test/Compatibility/TextCompatibilityTests.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System.IO; -using NUnit.Framework; - -namespace Google.ProtocolBuffers.Compatibility -{ - [TestFixture] - public class TextCompatibilityTests : CompatibilityTests - { - protected override object SerializeMessage(TMessage message) - { - StringWriter text = new StringWriter(); - message.PrintTo(text); - return text.ToString(); - } - - protected override TBuilder DeserializeMessage(object message, TBuilder builder, ExtensionRegistry registry) - { - TextFormat.Merge(new StringReader((string)message), registry, (IBuilder)builder); - return builder; - } - //This test can take a very long time to run. - [Test] - public override void RoundTripMessage2OptimizeSize() - { - //base.RoundTripMessage2OptimizeSize(); - } - - //This test can take a very long time to run. - [Test] - public override void RoundTripMessage2OptimizeSpeed() - { - //base.RoundTripMessage2OptimizeSpeed(); - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers.Test/Compatibility/XmlCompatibilityTests.cs b/csharp/src/ProtocolBuffers.Test/Compatibility/XmlCompatibilityTests.cs deleted file mode 100644 index 91d40d83..00000000 --- a/csharp/src/ProtocolBuffers.Test/Compatibility/XmlCompatibilityTests.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System.IO; -using System.Xml; -using Google.ProtocolBuffers.Serialization; -using NUnit.Framework; - -namespace Google.ProtocolBuffers.Compatibility -{ - [TestFixture] - public class XmlCompatibilityTests : CompatibilityTests - { - protected override object SerializeMessage(TMessage message) - { - StringWriter text = new StringWriter(); - XmlFormatWriter writer = XmlFormatWriter.CreateInstance(text); - writer.WriteMessage("root", message); - return text.ToString(); - } - - protected override TBuilder DeserializeMessage(object message, TBuilder builder, ExtensionRegistry registry) - { - XmlFormatReader reader = XmlFormatReader.CreateInstance((string)message); - return reader.Merge("root", builder, registry); - } - } - - [TestFixture] - public class XmlCompatibilityFormattedTests : CompatibilityTests - { - protected override object SerializeMessage(TMessage message) - { - StringWriter text = new StringWriter(); - XmlWriter xwtr = XmlWriter.Create(text, new XmlWriterSettings { Indent = true, IndentChars = " " }); - - XmlFormatWriter writer = XmlFormatWriter.CreateInstance(xwtr).SetOptions(XmlWriterOptions.OutputNestedArrays); - writer.WriteMessage("root", message); - return text.ToString(); - } - - protected override TBuilder DeserializeMessage(object message, TBuilder builder, ExtensionRegistry registry) - { - XmlFormatReader reader = XmlFormatReader.CreateInstance((string)message).SetOptions(XmlReaderOptions.ReadNestedArrays); - return reader.Merge("root", builder, registry); - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers.Test/Compatibility/google_message1.dat b/csharp/src/ProtocolBuffers.Test/Compatibility/google_message1.dat deleted file mode 100644 index bc0f064c..00000000 Binary files a/csharp/src/ProtocolBuffers.Test/Compatibility/google_message1.dat and /dev/null differ diff --git a/csharp/src/ProtocolBuffers.Test/Compatibility/google_message2.dat b/csharp/src/ProtocolBuffers.Test/Compatibility/google_message2.dat deleted file mode 100644 index 06c09441..00000000 Binary files a/csharp/src/ProtocolBuffers.Test/Compatibility/google_message2.dat and /dev/null differ diff --git a/csharp/src/ProtocolBuffers.Test/DeprecatedMemberTest.cs b/csharp/src/ProtocolBuffers.Test/DeprecatedMemberTest.cs index db64d37a..c962df54 100644 --- a/csharp/src/ProtocolBuffers.Test/DeprecatedMemberTest.cs +++ b/csharp/src/ProtocolBuffers.Test/DeprecatedMemberTest.cs @@ -1,9 +1,9 @@ using System; using System.Reflection; -using UnitTest.Issues.TestProtos; +using Google.Protobuf.TestProtos; using NUnit.Framework; -namespace Google.ProtocolBuffers +namespace Google.Protobuf { public class DeprecatedMemberTest { @@ -16,84 +16,8 @@ namespace Google.ProtocolBuffers [Test] public void TestDepreatedPrimitiveValue() { - AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("HasPrimitiveValue")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("PrimitiveValue")); - - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("HasPrimitiveValue")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("PrimitiveValue")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("ClearPrimitiveValue")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetPrimitiveValue")); - } - [Test] - public void TestDepreatedPrimitiveArray() - { - AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("PrimitiveArrayList")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("PrimitiveArrayCount")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetMethod("GetPrimitiveArray")); - - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("PrimitiveArrayList")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("PrimitiveArrayCount")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("GetPrimitiveArray")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetPrimitiveArray")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddPrimitiveArray")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddRangePrimitiveArray")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("ClearPrimitiveArray")); - } - [Test] - public void TestDepreatedMessageValue() - { - AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("HasMessageValue")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("MessageValue")); - - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("HasMessageValue")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("MessageValue")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("MergeMessageValue")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("ClearMessageValue")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetMessageValue", new[] { typeof(DeprecatedChild) })); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetMessageValue", new[] { typeof(DeprecatedChild.Builder) })); - } - [Test] - public void TestDepreatedMessageArray() - { - AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("MessageArrayList")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("MessageArrayCount")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetMethod("GetMessageArray")); - - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("MessageArrayList")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("MessageArrayCount")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("GetMessageArray")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetMessageArray", new[] { typeof(int), typeof(DeprecatedChild) })); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetMessageArray", new[] { typeof(int), typeof(DeprecatedChild.Builder) })); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddMessageArray", new[] { typeof(DeprecatedChild) })); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddMessageArray", new[] { typeof(DeprecatedChild.Builder) })); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddRangeMessageArray")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("ClearMessageArray")); - } - [Test] - public void TestDepreatedEnumValue() - { - AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("HasEnumValue")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("EnumValue")); - - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("HasEnumValue")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("EnumValue")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("ClearEnumValue")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetEnumValue")); + AssertIsDeprecated(typeof(TestDeprecatedFields).GetProperty("DeprecatedInt32")); } - [Test] - public void TestDepreatedEnumArray() - { - AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("EnumArrayList")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("EnumArrayCount")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetMethod("GetEnumArray")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("EnumArrayList")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("EnumArrayCount")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("GetEnumArray")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetEnumArray")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddEnumArray")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddRangeEnumArray")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("ClearEnumArray")); - } } } diff --git a/csharp/src/ProtocolBuffers.Test/DescriptorsTest.cs b/csharp/src/ProtocolBuffers.Test/DescriptorsTest.cs index 3c26f441..8c01e16a 100644 --- a/csharp/src/ProtocolBuffers.Test/DescriptorsTest.cs +++ b/csharp/src/ProtocolBuffers.Test/DescriptorsTest.cs @@ -34,11 +34,11 @@ #endregion -using Google.ProtocolBuffers.Descriptors; -using Google.ProtocolBuffers.TestProtos; +using Google.Protobuf.Descriptors; +using Google.Protobuf.TestProtos; using NUnit.Framework; -namespace Google.ProtocolBuffers +namespace Google.Protobuf { /// /// Tests for descriptors. (Not in its own namespace or broken up into individual classes as the @@ -49,21 +49,21 @@ namespace Google.ProtocolBuffers [Test] public void FileDescriptor() { - FileDescriptor file = Unittest.Descriptor; + FileDescriptor file = UnittestProto3.Descriptor; - Assert.AreEqual("google/protobuf/unittest.proto", file.Name); + Assert.AreEqual("google/protobuf/unittest_proto3.proto", file.Name); Assert.AreEqual("protobuf_unittest", file.Package); Assert.AreEqual("UnittestProto", file.Options.JavaOuterClassname); - Assert.AreEqual("google/protobuf/unittest.proto", file.Proto.Name); + Assert.AreEqual("google/protobuf/unittest_proto3.proto", file.Proto.Name); // unittest.proto doesn't have any public imports, but unittest_import.proto does. Assert.AreEqual(0, file.PublicDependencies.Count); - Assert.AreEqual(1, UnittestImport.Descriptor.PublicDependencies.Count); - Assert.AreEqual(UnittestImportPublic.Descriptor, UnittestImport.Descriptor.PublicDependencies[0]); + Assert.AreEqual(1, UnittestImportProto3.Descriptor.PublicDependencies.Count); + Assert.AreEqual(UnittestImportPublicProto3.Descriptor, UnittestImportProto3.Descriptor.PublicDependencies[0]); Assert.AreEqual(1, file.Dependencies.Count); - Assert.AreEqual(UnittestImport.Descriptor, file.Dependencies[0]); + Assert.AreEqual(UnittestImportProto3.Descriptor, file.Dependencies[0]); MessageDescriptor messageType = TestAllTypes.Descriptor; Assert.AreEqual(messageType, file.MessageTypes[0]); @@ -78,23 +78,12 @@ namespace Google.ProtocolBuffers Assert.AreEqual(file.EnumTypes[0], file.FindTypeByName("ForeignEnum")); Assert.Null(file.FindTypeByName("NoSuchType")); Assert.Null(file.FindTypeByName("protobuf_unittest.ForeignEnum")); - Assert.AreEqual(1, UnittestImport.Descriptor.EnumTypes.Count); - Assert.AreEqual("ImportEnum", UnittestImport.Descriptor.EnumTypes[0].Name); + Assert.AreEqual(1, UnittestImportProto3.Descriptor.EnumTypes.Count); + Assert.AreEqual("ImportEnum", UnittestImportProto3.Descriptor.EnumTypes[0].Name); for (int i = 0; i < file.EnumTypes.Count; i++) { Assert.AreEqual(i, file.EnumTypes[i].Index); } - - FieldDescriptor extension = Unittest.OptionalInt32Extension.Descriptor; - Assert.AreEqual(extension, file.Extensions[0]); - Assert.AreEqual(extension, file.FindTypeByName("optional_int32_extension")); - Assert.Null(file.FindTypeByName("no_such_ext")); - Assert.Null(file.FindTypeByName("protobuf_unittest.optional_int32_extension")); - Assert.AreEqual(0, UnittestImport.Descriptor.Extensions.Count); - for (int i = 0; i < file.Extensions.Count; i++) - { - Assert.AreEqual(i, file.Extensions[i].Index); - } } [Test] @@ -105,19 +94,20 @@ namespace Google.ProtocolBuffers Assert.AreEqual("TestAllTypes", messageType.Name); Assert.AreEqual("protobuf_unittest.TestAllTypes", messageType.FullName); - Assert.AreEqual(Unittest.Descriptor, messageType.File); - Assert.Null(messageType.ContainingType); - Assert.AreEqual(DescriptorProtos.MessageOptions.DefaultInstance, messageType.Options); - Assert.AreEqual("TestAllTypes", messageType.Proto.Name); + Assert.AreEqual(UnittestProto3.Descriptor, messageType.File); + Assert.IsNull(messageType.ContainingType); + Assert.IsNull(messageType.Options); + + Assert.AreEqual("TestAllTypes", messageType.Name); Assert.AreEqual("NestedMessage", nestedType.Name); Assert.AreEqual("protobuf_unittest.TestAllTypes.NestedMessage", nestedType.FullName); - Assert.AreEqual(Unittest.Descriptor, nestedType.File); + Assert.AreEqual(UnittestProto3.Descriptor, nestedType.File); Assert.AreEqual(messageType, nestedType.ContainingType); FieldDescriptor field = messageType.Fields[0]; - Assert.AreEqual("optional_int32", field.Name); - Assert.AreEqual(field, messageType.FindDescriptor("optional_int32")); + Assert.AreEqual("single_int32", field.Name); + Assert.AreEqual(field, messageType.FindDescriptor("single_int32")); Assert.Null(messageType.FindDescriptor("no_such_field")); Assert.AreEqual(field, messageType.FindFieldByNumber(1)); Assert.Null(messageType.FindFieldByNumber(571283)); @@ -146,115 +136,66 @@ namespace Google.ProtocolBuffers public void FieldDescriptor() { MessageDescriptor messageType = TestAllTypes.Descriptor; - FieldDescriptor primitiveField = messageType.FindDescriptor("optional_int32"); - FieldDescriptor enumField = messageType.FindDescriptor("optional_nested_enum"); - FieldDescriptor messageField = messageType.FindDescriptor("optional_foreign_message"); - FieldDescriptor cordField = messageType.FindDescriptor("optional_cord"); - FieldDescriptor extension = Unittest.OptionalInt32Extension.Descriptor; - FieldDescriptor nestedExtension = TestRequired.Single.Descriptor; + FieldDescriptor primitiveField = messageType.FindDescriptor("single_int32"); + FieldDescriptor enumField = messageType.FindDescriptor("single_nested_enum"); + FieldDescriptor messageField = messageType.FindDescriptor("single_foreign_message"); - Assert.AreEqual("optional_int32", primitiveField.Name); - Assert.AreEqual("protobuf_unittest.TestAllTypes.optional_int32", + Assert.AreEqual("single_int32", primitiveField.Name); + Assert.AreEqual("protobuf_unittest.TestAllTypes.single_int32", primitiveField.FullName); Assert.AreEqual(1, primitiveField.FieldNumber); Assert.AreEqual(messageType, primitiveField.ContainingType); - Assert.AreEqual(Unittest.Descriptor, primitiveField.File); + Assert.AreEqual(UnittestProto3.Descriptor, primitiveField.File); Assert.AreEqual(FieldType.Int32, primitiveField.FieldType); Assert.AreEqual(MappedType.Int32, primitiveField.MappedType); - Assert.AreEqual(DescriptorProtos.FieldOptions.DefaultInstance, primitiveField.Options); - Assert.IsFalse(primitiveField.IsExtension); - Assert.AreEqual("optional_int32", primitiveField.Proto.Name); - - Assert.AreEqual("optional_nested_enum", enumField.Name); + Assert.IsNull(primitiveField.Options); + + Assert.AreEqual("single_nested_enum", enumField.Name); Assert.AreEqual(FieldType.Enum, enumField.FieldType); Assert.AreEqual(MappedType.Enum, enumField.MappedType); // Assert.AreEqual(TestAllTypes.Types.NestedEnum.DescriptorProtoFile, enumField.EnumType); - Assert.AreEqual("optional_foreign_message", messageField.Name); + Assert.AreEqual("single_foreign_message", messageField.Name); Assert.AreEqual(FieldType.Message, messageField.FieldType); Assert.AreEqual(MappedType.Message, messageField.MappedType); Assert.AreEqual(ForeignMessage.Descriptor, messageField.MessageType); - - Assert.AreEqual("optional_cord", cordField.Name); - Assert.AreEqual(FieldType.String, cordField.FieldType); - Assert.AreEqual(MappedType.String, cordField.MappedType); - Assert.AreEqual(DescriptorProtos.FieldOptions.Types.CType.CORD, cordField.Options.Ctype); - - Assert.AreEqual("optional_int32_extension", extension.Name); - Assert.AreEqual("protobuf_unittest.optional_int32_extension", extension.FullName); - Assert.AreEqual(1, extension.FieldNumber); - Assert.AreEqual(TestAllExtensions.Descriptor, extension.ContainingType); - Assert.AreEqual(Unittest.Descriptor, extension.File); - Assert.AreEqual(FieldType.Int32, extension.FieldType); - Assert.AreEqual(MappedType.Int32, extension.MappedType); - Assert.AreEqual(DescriptorProtos.FieldOptions.DefaultInstance, - extension.Options); - Assert.IsTrue(extension.IsExtension); - Assert.AreEqual(null, extension.ExtensionScope); - Assert.AreEqual("optional_int32_extension", extension.Proto.Name); - - Assert.AreEqual("single", nestedExtension.Name); - Assert.AreEqual("protobuf_unittest.TestRequired.single", - nestedExtension.FullName); - Assert.AreEqual(TestRequired.Descriptor, - nestedExtension.ExtensionScope); } [Test] public void FieldDescriptorLabel() { - FieldDescriptor requiredField = - TestRequired.Descriptor.FindDescriptor("a"); - FieldDescriptor optionalField = - TestAllTypes.Descriptor.FindDescriptor("optional_int32"); + FieldDescriptor singleField = + TestAllTypes.Descriptor.FindDescriptor("single_int32"); FieldDescriptor repeatedField = TestAllTypes.Descriptor.FindDescriptor("repeated_int32"); - Assert.IsTrue(requiredField.IsRequired); - Assert.IsFalse(requiredField.IsRepeated); - Assert.IsFalse(optionalField.IsRequired); - Assert.IsFalse(optionalField.IsRepeated); + Assert.IsFalse(singleField.IsRequired); + Assert.IsFalse(singleField.IsRepeated); Assert.IsFalse(repeatedField.IsRequired); Assert.IsTrue(repeatedField.IsRepeated); } - [Test] - public void FieldDescriptorDefault() - { - MessageDescriptor d = TestAllTypes.Descriptor; - Assert.IsFalse(d.FindDescriptor("optional_int32").HasDefaultValue); - Assert.AreEqual(0, d.FindDescriptor("optional_int32").DefaultValue); - Assert.IsTrue(d.FindDescriptor("default_int32").HasDefaultValue); - Assert.AreEqual(41, d.FindDescriptor("default_int32").DefaultValue); - - d = TestExtremeDefaultValues.Descriptor; - Assert.AreEqual(TestExtremeDefaultValues.DefaultInstance.EscapedBytes, - d.FindDescriptor("escaped_bytes").DefaultValue); - Assert.AreEqual(uint.MaxValue, d.FindDescriptor("large_uint32").DefaultValue); - Assert.AreEqual(ulong.MaxValue, d.FindDescriptor("large_uint64").DefaultValue); - } [Test] public void EnumDescriptor() { // Note: this test is a bit different to the Java version because there's no static way of getting to the descriptor - EnumDescriptor enumType = Unittest.Descriptor.FindTypeByName("ForeignEnum"); + EnumDescriptor enumType = UnittestProto3.Descriptor.FindTypeByName("ForeignEnum"); EnumDescriptor nestedType = TestAllTypes.Descriptor.FindDescriptor("NestedEnum"); Assert.AreEqual("ForeignEnum", enumType.Name); Assert.AreEqual("protobuf_unittest.ForeignEnum", enumType.FullName); - Assert.AreEqual(Unittest.Descriptor, enumType.File); + Assert.AreEqual(UnittestProto3.Descriptor, enumType.File); Assert.Null(enumType.ContainingType); - Assert.AreEqual(DescriptorProtos.EnumOptions.DefaultInstance, - enumType.Options); + Assert.Null(enumType.Options); Assert.AreEqual("NestedEnum", nestedType.Name); Assert.AreEqual("protobuf_unittest.TestAllTypes.NestedEnum", nestedType.FullName); - Assert.AreEqual(Unittest.Descriptor, nestedType.File); + Assert.AreEqual(UnittestProto3.Descriptor, nestedType.File); Assert.AreEqual(TestAllTypes.Descriptor, nestedType.ContainingType); EnumValueDescriptor value = enumType.FindValueByName("FOREIGN_FOO"); - Assert.AreEqual(value, enumType.Values[0]); + Assert.AreEqual(value, enumType.Values[1]); Assert.AreEqual("FOREIGN_FOO", value.Name); Assert.AreEqual(4, value.Number); Assert.AreEqual((int) ForeignEnum.FOREIGN_FOO, value.Number); @@ -265,22 +206,5 @@ namespace Google.ProtocolBuffers Assert.AreEqual(i, enumType.Values[i].Index); } } - - - [Test] - public void CustomOptions() - { - MessageDescriptor descriptor = TestMessageWithCustomOptions.Descriptor; - Assert.IsTrue(descriptor.Options.HasExtension(UnittestCustomOptions.MessageOpt1)); - Assert.AreEqual(-56, descriptor.Options.GetExtension(UnittestCustomOptions.MessageOpt1)); - - - FieldDescriptor field = descriptor.FindFieldByName("field1"); - Assert.NotNull(field); - - Assert.IsTrue(field.Options.HasExtension(UnittestCustomOptions.FieldOpt1)); - Assert.AreEqual(8765432109uL, field.Options.GetExtension(UnittestCustomOptions.FieldOpt1)); - - } } } \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers.Test/DynamicMessageTest.cs b/csharp/src/ProtocolBuffers.Test/DynamicMessageTest.cs deleted file mode 100644 index f60db213..00000000 --- a/csharp/src/ProtocolBuffers.Test/DynamicMessageTest.cs +++ /dev/null @@ -1,276 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using Google.ProtocolBuffers.Descriptors; -using Google.ProtocolBuffers.TestProtos; -using NUnit.Framework; - -namespace Google.ProtocolBuffers -{ - public class DynamicMessageTest - { - private ReflectionTester reflectionTester; - private ReflectionTester extensionsReflectionTester; - private ReflectionTester packedReflectionTester; - - public DynamicMessageTest() - { - reflectionTester = ReflectionTester.CreateTestAllTypesInstance(); - extensionsReflectionTester = ReflectionTester.CreateTestAllExtensionsInstance(); - packedReflectionTester = ReflectionTester.CreateTestPackedTypesInstance(); - } - - [Test] - public void DynamicMessageAccessors() - { - IBuilder builder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor); - reflectionTester.SetAllFieldsViaReflection(builder); - IMessage message = builder.WeakBuild(); - reflectionTester.AssertAllFieldsSetViaReflection(message); - } - - [Test] - public void DoubleBuildError() - { - DynamicMessage.Builder builder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor); - builder.Build(); - Assert.Throws(() => builder.Build()); - } - - [Test] - public void DynamicMessageSettersRejectNull() - { - IBuilder builder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor); - reflectionTester.AssertReflectionSettersRejectNull(builder); - } - - [Test] - public void DynamicMessageExtensionAccessors() - { - // We don't need to extensively test DynamicMessage's handling of - // extensions because, frankly, it doesn't do anything special with them. - // It treats them just like any other fields. - IBuilder builder = DynamicMessage.CreateBuilder(TestAllExtensions.Descriptor); - extensionsReflectionTester.SetAllFieldsViaReflection(builder); - IMessage message = builder.WeakBuild(); - extensionsReflectionTester.AssertAllFieldsSetViaReflection(message); - } - - [Test] - public void DynamicMessageExtensionSettersRejectNull() - { - IBuilder builder = DynamicMessage.CreateBuilder(TestAllExtensions.Descriptor); - extensionsReflectionTester.AssertReflectionSettersRejectNull(builder); - } - - [Test] - public void DynamicMessageRepeatedSetters() - { - IBuilder builder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor); - reflectionTester.SetAllFieldsViaReflection(builder); - reflectionTester.ModifyRepeatedFieldsViaReflection(builder); - IMessage message = builder.WeakBuild(); - reflectionTester.AssertRepeatedFieldsModifiedViaReflection(message); - } - - [Test] - public void DynamicMessageRepeatedSettersRejectNull() - { - IBuilder builder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor); - reflectionTester.AssertReflectionRepeatedSettersRejectNull(builder); - } - - [Test] - public void DynamicMessageDefaults() - { - reflectionTester.AssertClearViaReflection(DynamicMessage.GetDefaultInstance(TestAllTypes.Descriptor)); - reflectionTester.AssertClearViaReflection(DynamicMessage.CreateBuilder(TestAllTypes.Descriptor).Build()); - } - - [Test] - public void DynamicMessageSerializedSize() - { - TestAllTypes message = TestUtil.GetAllSet(); - - IBuilder dynamicBuilder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor); - reflectionTester.SetAllFieldsViaReflection(dynamicBuilder); - IMessage dynamicMessage = dynamicBuilder.WeakBuild(); - - Assert.AreEqual(message.SerializedSize, dynamicMessage.SerializedSize); - } - - [Test] - public void DynamicMessageSerialization() - { - IBuilder builder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor); - reflectionTester.SetAllFieldsViaReflection(builder); - IMessage message = builder.WeakBuild(); - - ByteString rawBytes = message.ToByteString(); - TestAllTypes message2 = TestAllTypes.ParseFrom(rawBytes); - - TestUtil.AssertAllFieldsSet(message2); - - // In fact, the serialized forms should be exactly the same, byte-for-byte. - Assert.AreEqual(TestUtil.GetAllSet().ToByteString(), rawBytes); - } - - [Test] - public void DynamicMessageParsing() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - TestUtil.SetAllFields(builder); - TestAllTypes message = builder.Build(); - - ByteString rawBytes = message.ToByteString(); - - IMessage message2 = DynamicMessage.ParseFrom(TestAllTypes.Descriptor, rawBytes); - reflectionTester.AssertAllFieldsSetViaReflection(message2); - } - - [Test] - public void DynamicMessagePackedSerialization() - { - IBuilder builder = DynamicMessage.CreateBuilder(TestPackedTypes.Descriptor); - packedReflectionTester.SetPackedFieldsViaReflection(builder); - IMessage message = builder.WeakBuild(); - - ByteString rawBytes = message.ToByteString(); - TestPackedTypes message2 = TestPackedTypes.ParseFrom(rawBytes); - - TestUtil.AssertPackedFieldsSet(message2); - - // In fact, the serialized forms should be exactly the same, byte-for-byte. - Assert.AreEqual(TestUtil.GetPackedSet().ToByteString(), rawBytes); - } - - [Test] - public void DynamicMessagePackedParsing() - { - TestPackedTypes.Builder builder = TestPackedTypes.CreateBuilder(); - TestUtil.SetPackedFields(builder); - TestPackedTypes message = builder.Build(); - - ByteString rawBytes = message.ToByteString(); - - IMessage message2 = DynamicMessage.ParseFrom(TestPackedTypes.Descriptor, rawBytes); - packedReflectionTester.AssertPackedFieldsSetViaReflection(message2); - } - - [Test] - public void DynamicMessageCopy() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - TestUtil.SetAllFields(builder); - TestAllTypes message = builder.Build(); - - DynamicMessage copy = DynamicMessage.CreateBuilder(message).Build(); - reflectionTester.AssertAllFieldsSetViaReflection(copy); - - // Oneof - FieldDescriptor bytesField = - TestAllTypes.Descriptor.FindFieldByName("oneof_bytes"); - FieldDescriptor uint32Field = - TestAllTypes.Descriptor.FindFieldByName("oneof_uint32"); - Assert.True(copy.HasField(bytesField)); - Assert.False(copy.HasField(uint32Field)); - - DynamicMessage.Builder dynamicBuilder = DynamicMessage.CreateBuilder(message); - dynamicBuilder[uint32Field] = 123U; - DynamicMessage copy2 = dynamicBuilder.Build(); - Assert.IsFalse(copy2.HasField(bytesField)); - Assert.IsTrue(copy2.HasField(uint32Field)); - Assert.AreEqual(123U, copy2[uint32Field]); - } - - [Test] - public void ToBuilder() - { - DynamicMessage.Builder builder = - DynamicMessage.CreateBuilder(TestAllTypes.Descriptor); - reflectionTester.SetAllFieldsViaReflection(builder); - int unknownFieldNum = 9; - ulong unknownFieldVal = 90; - builder.SetUnknownFields(UnknownFieldSet.CreateBuilder() - .AddField(unknownFieldNum, - UnknownField.CreateBuilder().AddVarint(unknownFieldVal).Build()) - .Build()); - DynamicMessage message = builder.Build(); - - DynamicMessage derived = message.ToBuilder().Build(); - reflectionTester.AssertAllFieldsSetViaReflection(derived); - - IList values = derived.UnknownFields.FieldDictionary[unknownFieldNum].VarintList; - Assert.AreEqual(1, values.Count); - Assert.AreEqual(unknownFieldVal, values[0]); - } - - [Test] - public void DynamicOneofMessage() - { - DynamicMessage.Builder builder = - DynamicMessage.CreateBuilder(TestAllTypes.Descriptor); - OneofDescriptor oneof = TestAllTypes.Descriptor.Oneofs[0]; - Assert.False(builder.HasOneof(oneof)); - Assert.AreSame(null, builder.OneofFieldDescriptor(oneof)); - - reflectionTester.SetAllFieldsViaReflection(builder); - Assert.True(builder.HasOneof(oneof)); - FieldDescriptor field = oneof.Field(3); - Assert.AreSame(field, builder.OneofFieldDescriptor(oneof)); - Assert.AreEqual(TestUtil.ToBytes("604"), builder[field]); - - DynamicMessage message = builder.BuildPartial(); - Assert.IsTrue(message.HasOneof(oneof)); - - DynamicMessage.Builder mergedBuilder = - DynamicMessage.CreateBuilder(TestAllTypes.Descriptor); - FieldDescriptor mergedField = oneof.Field(0); - mergedBuilder[mergedField] = 123U; - Assert.IsTrue(mergedBuilder.HasField(mergedField)); - mergedBuilder.MergeFrom(message); - Assert.IsTrue(mergedBuilder.HasField(field)); - Assert.IsFalse(mergedBuilder.HasField(mergedField)); - - mergedBuilder.ClearOneof(oneof); - Assert.AreSame(null, mergedBuilder.OneofFieldDescriptor(oneof)); - message = mergedBuilder.Build(); - Assert.AreSame(null, message.OneofFieldDescriptor(oneof)); - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers.Test/ExtendableMessageTest.cs b/csharp/src/ProtocolBuffers.Test/ExtendableMessageTest.cs deleted file mode 100644 index 2aaf39c8..00000000 --- a/csharp/src/ProtocolBuffers.Test/ExtendableMessageTest.cs +++ /dev/null @@ -1,200 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using Google.ProtocolBuffers.TestProtos; -using NUnit.Framework; - -namespace Google.ProtocolBuffers -{ - public class ExtendableMessageTest - { - [Test] - public void ExtensionWriterInvalidExtension() - { - Assert.Throws(() => - TestPackedExtensions.CreateBuilder()[Unittest.OptionalForeignMessageExtension.Descriptor] = - ForeignMessage.DefaultInstance); - } - - [Test] - public void ExtensionWriterTest() - { - TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder() - .SetExtension(Unittest.DefaultBoolExtension, true) - .SetExtension(Unittest.DefaultBytesExtension, ByteString.CopyFromUtf8("123")) - .SetExtension(Unittest.DefaultCordExtension, "123") - .SetExtension(Unittest.DefaultDoubleExtension, 123) - .SetExtension(Unittest.DefaultFixed32Extension, 123u) - .SetExtension(Unittest.DefaultFixed64Extension, 123u) - .SetExtension(Unittest.DefaultFloatExtension, 123) - .SetExtension(Unittest.DefaultForeignEnumExtension, ForeignEnum.FOREIGN_BAZ) - .SetExtension(Unittest.DefaultImportEnumExtension, ImportEnum.IMPORT_BAZ) - .SetExtension(Unittest.DefaultInt32Extension, 123) - .SetExtension(Unittest.DefaultInt64Extension, 123) - .SetExtension(Unittest.DefaultNestedEnumExtension, TestAllTypes.Types.NestedEnum.FOO) - .SetExtension(Unittest.DefaultSfixed32Extension, 123) - .SetExtension(Unittest.DefaultSfixed64Extension, 123) - .SetExtension(Unittest.DefaultSint32Extension, 123) - .SetExtension(Unittest.DefaultSint64Extension, 123) - .SetExtension(Unittest.DefaultStringExtension, "123") - .SetExtension(Unittest.DefaultStringPieceExtension, "123") - .SetExtension(Unittest.DefaultUint32Extension, 123u) - .SetExtension(Unittest.DefaultUint64Extension, 123u) - //Optional - .SetExtension(Unittest.OptionalBoolExtension, true) - .SetExtension(Unittest.OptionalBytesExtension, ByteString.CopyFromUtf8("123")) - .SetExtension(Unittest.OptionalCordExtension, "123") - .SetExtension(Unittest.OptionalDoubleExtension, 123) - .SetExtension(Unittest.OptionalFixed32Extension, 123u) - .SetExtension(Unittest.OptionalFixed64Extension, 123u) - .SetExtension(Unittest.OptionalFloatExtension, 123) - .SetExtension(Unittest.OptionalForeignEnumExtension, ForeignEnum.FOREIGN_BAZ) - .SetExtension(Unittest.OptionalImportEnumExtension, ImportEnum.IMPORT_BAZ) - .SetExtension(Unittest.OptionalInt32Extension, 123) - .SetExtension(Unittest.OptionalInt64Extension, 123) - .SetExtension(Unittest.OptionalNestedEnumExtension, TestAllTypes.Types.NestedEnum.FOO) - .SetExtension(Unittest.OptionalSfixed32Extension, 123) - .SetExtension(Unittest.OptionalSfixed64Extension, 123) - .SetExtension(Unittest.OptionalSint32Extension, 123) - .SetExtension(Unittest.OptionalSint64Extension, 123) - .SetExtension(Unittest.OptionalStringExtension, "123") - .SetExtension(Unittest.OptionalStringPieceExtension, "123") - .SetExtension(Unittest.OptionalUint32Extension, 123u) - .SetExtension(Unittest.OptionalUint64Extension, 123u) - //Repeated - .AddExtension(Unittest.RepeatedBoolExtension, true) - .AddExtension(Unittest.RepeatedBytesExtension, ByteString.CopyFromUtf8("123")) - .AddExtension(Unittest.RepeatedCordExtension, "123") - .AddExtension(Unittest.RepeatedDoubleExtension, 123) - .AddExtension(Unittest.RepeatedFixed32Extension, 123u) - .AddExtension(Unittest.RepeatedFixed64Extension, 123u) - .AddExtension(Unittest.RepeatedFloatExtension, 123) - .AddExtension(Unittest.RepeatedForeignEnumExtension, ForeignEnum.FOREIGN_BAZ) - .AddExtension(Unittest.RepeatedImportEnumExtension, ImportEnum.IMPORT_BAZ) - .AddExtension(Unittest.RepeatedInt32Extension, 123) - .AddExtension(Unittest.RepeatedInt64Extension, 123) - .AddExtension(Unittest.RepeatedNestedEnumExtension, TestAllTypes.Types.NestedEnum.FOO) - .AddExtension(Unittest.RepeatedSfixed32Extension, 123) - .AddExtension(Unittest.RepeatedSfixed64Extension, 123) - .AddExtension(Unittest.RepeatedSint32Extension, 123) - .AddExtension(Unittest.RepeatedSint64Extension, 123) - .AddExtension(Unittest.RepeatedStringExtension, "123") - .AddExtension(Unittest.RepeatedStringPieceExtension, "123") - .AddExtension(Unittest.RepeatedUint32Extension, 123u) - .AddExtension(Unittest.RepeatedUint64Extension, 123u) - ; - TestAllExtensions msg = builder.Build(); - - ExtensionRegistry registry = ExtensionRegistry.CreateInstance(); - Unittest.RegisterAllExtensions(registry); - - TestAllExtensions.Builder copyBuilder = TestAllExtensions.CreateBuilder().MergeFrom(msg.ToByteArray(), - registry); - TestAllExtensions copy = copyBuilder.Build(); - - Assert.AreEqual(msg.ToByteArray(), copy.ToByteArray()); - - Assert.AreEqual(true, copy.GetExtension(Unittest.DefaultBoolExtension)); - Assert.AreEqual(ByteString.CopyFromUtf8("123"), copy.GetExtension(Unittest.DefaultBytesExtension)); - Assert.AreEqual("123", copy.GetExtension(Unittest.DefaultCordExtension)); - Assert.AreEqual(123, copy.GetExtension(Unittest.DefaultDoubleExtension)); - Assert.AreEqual(123u, copy.GetExtension(Unittest.DefaultFixed32Extension)); - Assert.AreEqual(123u, copy.GetExtension(Unittest.DefaultFixed64Extension)); - Assert.AreEqual(123, copy.GetExtension(Unittest.DefaultFloatExtension)); - Assert.AreEqual(ForeignEnum.FOREIGN_BAZ, copy.GetExtension(Unittest.DefaultForeignEnumExtension)); - Assert.AreEqual(ImportEnum.IMPORT_BAZ, copy.GetExtension(Unittest.DefaultImportEnumExtension)); - Assert.AreEqual(123, copy.GetExtension(Unittest.DefaultInt32Extension)); - Assert.AreEqual(123, copy.GetExtension(Unittest.DefaultInt64Extension)); - Assert.AreEqual(TestAllTypes.Types.NestedEnum.FOO, - copy.GetExtension(Unittest.DefaultNestedEnumExtension)); - Assert.AreEqual(123, copy.GetExtension(Unittest.DefaultSfixed32Extension)); - Assert.AreEqual(123, copy.GetExtension(Unittest.DefaultSfixed64Extension)); - Assert.AreEqual(123, copy.GetExtension(Unittest.DefaultSint32Extension)); - Assert.AreEqual(123, copy.GetExtension(Unittest.DefaultSint64Extension)); - Assert.AreEqual("123", copy.GetExtension(Unittest.DefaultStringExtension)); - Assert.AreEqual("123", copy.GetExtension(Unittest.DefaultStringPieceExtension)); - Assert.AreEqual(123u, copy.GetExtension(Unittest.DefaultUint32Extension)); - Assert.AreEqual(123u, copy.GetExtension(Unittest.DefaultUint64Extension)); - - Assert.AreEqual(true, copy.GetExtension(Unittest.OptionalBoolExtension)); - Assert.AreEqual(ByteString.CopyFromUtf8("123"), copy.GetExtension(Unittest.OptionalBytesExtension)); - Assert.AreEqual("123", copy.GetExtension(Unittest.OptionalCordExtension)); - Assert.AreEqual(123, copy.GetExtension(Unittest.OptionalDoubleExtension)); - Assert.AreEqual(123u, copy.GetExtension(Unittest.OptionalFixed32Extension)); - Assert.AreEqual(123u, copy.GetExtension(Unittest.OptionalFixed64Extension)); - Assert.AreEqual(123, copy.GetExtension(Unittest.OptionalFloatExtension)); - Assert.AreEqual(ForeignEnum.FOREIGN_BAZ, copy.GetExtension(Unittest.OptionalForeignEnumExtension)); - Assert.AreEqual(ImportEnum.IMPORT_BAZ, copy.GetExtension(Unittest.OptionalImportEnumExtension)); - Assert.AreEqual(123, copy.GetExtension(Unittest.OptionalInt32Extension)); - Assert.AreEqual(123, copy.GetExtension(Unittest.OptionalInt64Extension)); - Assert.AreEqual(TestAllTypes.Types.NestedEnum.FOO, - copy.GetExtension(Unittest.OptionalNestedEnumExtension)); - Assert.AreEqual(123, copy.GetExtension(Unittest.OptionalSfixed32Extension)); - Assert.AreEqual(123, copy.GetExtension(Unittest.OptionalSfixed64Extension)); - Assert.AreEqual(123, copy.GetExtension(Unittest.OptionalSint32Extension)); - Assert.AreEqual(123, copy.GetExtension(Unittest.OptionalSint64Extension)); - Assert.AreEqual("123", copy.GetExtension(Unittest.OptionalStringExtension)); - Assert.AreEqual("123", copy.GetExtension(Unittest.OptionalStringPieceExtension)); - Assert.AreEqual(123u, copy.GetExtension(Unittest.OptionalUint32Extension)); - Assert.AreEqual(123u, copy.GetExtension(Unittest.OptionalUint64Extension)); - - Assert.AreEqual(true, copy.GetExtension(Unittest.RepeatedBoolExtension, 0)); - Assert.AreEqual(ByteString.CopyFromUtf8("123"), - copy.GetExtension(Unittest.RepeatedBytesExtension, 0)); - Assert.AreEqual("123", copy.GetExtension(Unittest.RepeatedCordExtension, 0)); - Assert.AreEqual(123, copy.GetExtension(Unittest.RepeatedDoubleExtension, 0)); - Assert.AreEqual(123u, copy.GetExtension(Unittest.RepeatedFixed32Extension, 0)); - Assert.AreEqual(123u, copy.GetExtension(Unittest.RepeatedFixed64Extension, 0)); - Assert.AreEqual(123, copy.GetExtension(Unittest.RepeatedFloatExtension, 0)); - Assert.AreEqual(ForeignEnum.FOREIGN_BAZ, - copy.GetExtension(Unittest.RepeatedForeignEnumExtension, 0)); - Assert.AreEqual(ImportEnum.IMPORT_BAZ, copy.GetExtension(Unittest.RepeatedImportEnumExtension, 0)); - Assert.AreEqual(123, copy.GetExtension(Unittest.RepeatedInt32Extension, 0)); - Assert.AreEqual(123, copy.GetExtension(Unittest.RepeatedInt64Extension, 0)); - Assert.AreEqual(TestAllTypes.Types.NestedEnum.FOO, - copy.GetExtension(Unittest.RepeatedNestedEnumExtension, 0)); - Assert.AreEqual(123, copy.GetExtension(Unittest.RepeatedSfixed32Extension, 0)); - Assert.AreEqual(123, copy.GetExtension(Unittest.RepeatedSfixed64Extension, 0)); - Assert.AreEqual(123, copy.GetExtension(Unittest.RepeatedSint32Extension, 0)); - Assert.AreEqual(123, copy.GetExtension(Unittest.RepeatedSint64Extension, 0)); - Assert.AreEqual("123", copy.GetExtension(Unittest.RepeatedStringExtension, 0)); - Assert.AreEqual("123", copy.GetExtension(Unittest.RepeatedStringPieceExtension, 0)); - Assert.AreEqual(123u, copy.GetExtension(Unittest.RepeatedUint32Extension, 0)); - Assert.AreEqual(123u, copy.GetExtension(Unittest.RepeatedUint64Extension, 0)); - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers.Test/FieldPresenceTest.cs b/csharp/src/ProtocolBuffers.Test/FieldPresenceTest.cs deleted file mode 100644 index 66214221..00000000 --- a/csharp/src/ProtocolBuffers.Test/FieldPresenceTest.cs +++ /dev/null @@ -1,198 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2015 Google Inc. All rights reserved. -// Author: jieluo@google.com (Jie Luo) -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using Google.ProtocolBuffers.Descriptors; -using Google.ProtocolBuffers.TestProtos.Proto3; -using NUnit.Framework; - -namespace Google.ProtocolBuffers -{ - public class FieldPresenceTest - { - private void CheckHasMethodRemoved(Type proto2Type, Type proto3Type, string name) - { - Assert.NotNull(proto2Type.GetProperty(name)); - Assert.NotNull(proto2Type.GetProperty("Has" + name)); - Assert.NotNull(proto3Type.GetProperty(name)); - Assert.Null(proto3Type.GetProperty("Has" + name)); - } - - [Test] - public void TestHasMethod() - { - // Optional non-message fields don't have HasFoo method generated - Type proto2Type = typeof(Google.ProtocolBuffers.TestProtos.TestAllTypes); - Type proto3Type = typeof(TestAllTypes); - CheckHasMethodRemoved(proto2Type, proto3Type, "OptionalInt32"); - CheckHasMethodRemoved(proto2Type, proto3Type, "OptionalString"); - CheckHasMethodRemoved(proto2Type, proto3Type, "OptionalBytes"); - CheckHasMethodRemoved(proto2Type, proto3Type, "OptionalNestedEnum"); - - Type proto2BuilderType = typeof(Google.ProtocolBuffers.TestProtos.TestAllTypes.Builder); - Type proto3BuilderType = typeof(TestAllTypes.Builder); - CheckHasMethodRemoved(proto2BuilderType, proto3BuilderType, "OptionalInt32"); - CheckHasMethodRemoved(proto2BuilderType, proto3BuilderType, "OptionalString"); - CheckHasMethodRemoved(proto2BuilderType, proto3BuilderType, "OptionalBytes"); - CheckHasMethodRemoved(proto2BuilderType, proto3BuilderType, "OptionalNestedEnum"); - - // message fields still have the HasFoo method generated - Assert.IsFalse(TestAllTypes.CreateBuilder().Build().HasOptionalNestedMessage); - Assert.IsFalse(TestAllTypes.CreateBuilder().HasOptionalNestedMessage); - - // oneof fields don't have the HasFoo method (even for message types) - CheckHasMethodRemoved(proto2Type, proto3Type, "OneofUint32"); - CheckHasMethodRemoved(proto2Type, proto3Type, "OneofString"); - CheckHasMethodRemoved(proto2Type, proto3Type, "OneofNestedMessage"); - - CheckHasMethodRemoved(proto2BuilderType, proto3BuilderType, "OneofUint32"); - CheckHasMethodRemoved(proto2BuilderType, proto3BuilderType, "OneofString"); - CheckHasMethodRemoved(proto2BuilderType, proto3BuilderType, "OneofNestedMessage"); - } - - [Test] - public void TestFieldPresence() - { - // Optional non-message fields set to their default value are treated the same - // way as not set. - - // Serialization will ignore such fields. - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - builder.SetOptionalInt32(0); - builder.SetOptionalString(""); - builder.SetOptionalBytes(ByteString.Empty); - builder.SetOptionalNestedEnum(TestAllTypes.Types.NestedEnum.FOO); - TestAllTypes message = builder.Build(); - Assert.AreEqual(0, message.SerializedSize); - - // Test merge - TestAllTypes.Builder a = TestAllTypes.CreateBuilder(); - a.SetOptionalInt32(1); - a.SetOptionalString("x"); - a.SetOptionalBytes(ByteString.CopyFromUtf8("y")); - a.SetOptionalNestedEnum(TestAllTypes.Types.NestedEnum.BAR); - a.MergeFrom(message); - TestAllTypes messageA = a.Build(); - Assert.AreEqual(1, messageA.OptionalInt32); - Assert.AreEqual("x", messageA.OptionalString); - Assert.AreEqual(ByteString.CopyFromUtf8("y"), messageA.OptionalBytes); - Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAR, messageA.OptionalNestedEnum); - - // equals/hashCode should produce the same results - TestAllTypes empty = TestAllTypes.CreateBuilder().Build(); - Assert.IsTrue(empty.Equals(message)); - Assert.IsTrue(message.Equals(empty)); - Assert.AreEqual(empty.GetHashCode(), message.GetHashCode()); - } - - [Test] - public void TestFieldPresenceReflection() - { - MessageDescriptor descriptor = TestAllTypes.Descriptor; - FieldDescriptor optionalInt32Field = descriptor.FindFieldByName("optional_int32"); - FieldDescriptor optionalStringField = descriptor.FindFieldByName("optional_string"); - FieldDescriptor optionalBytesField = descriptor.FindFieldByName("optional_bytes"); - FieldDescriptor optionalNestedEnumField = descriptor.FindFieldByName("optional_nested_enum"); - FieldDescriptor oneofUint32Field = descriptor.FindFieldByName("oneof_uint32"); - - TestAllTypes message = TestAllTypes.CreateBuilder().Build(); - Assert.IsFalse(message.HasField(optionalInt32Field)); - Assert.IsFalse(message.HasField(optionalStringField)); - Assert.IsFalse(message.HasField(optionalBytesField)); - Assert.IsFalse(message.HasField(optionalNestedEnumField)); - - // Set to default value is seen as not present for optional fields. - // Set to default value is seen as present for oneof fields. - message = TestAllTypes.CreateBuilder() - .SetOptionalInt32(0) - .SetOptionalString("") - .SetOptionalBytes(ByteString.Empty) - .SetOptionalNestedEnum(TestAllTypes.Types.NestedEnum.FOO) - .SetOneofUint32(0U) - .Build(); - Assert.IsFalse(message.HasField(optionalInt32Field)); - Assert.IsFalse(message.HasField(optionalStringField)); - Assert.IsFalse(message.HasField(optionalBytesField)); - Assert.IsFalse(message.HasField(optionalNestedEnumField)); - Assert.IsTrue(message.HasField(oneofUint32Field)); - Assert.AreEqual(1, message.AllFields.Count); - - // Set to non-defalut value is seen as present - message = TestAllTypes.CreateBuilder() - .SetOptionalInt32(1) - .SetOptionalString("x") - .SetOptionalBytes(ByteString.CopyFromUtf8("y")) - .SetOptionalNestedEnum(TestAllTypes.Types.NestedEnum.BAR) - .Build(); - Assert.IsTrue(message.HasField(optionalInt32Field)); - Assert.IsTrue(message.HasField(optionalStringField)); - Assert.IsTrue(message.HasField(optionalBytesField)); - Assert.IsTrue(message.HasField(optionalNestedEnumField)); - Assert.AreEqual(4, message.AllFields.Count); - } - - [Test] - public void TestMessageField() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - Assert.IsFalse(builder.HasOptionalNestedMessage); - Assert.IsFalse(builder.Build().HasOptionalNestedMessage); - - // Unlike non-message fields, if we set default value to message field, the field - // shoule be seem as present. - builder.SetOptionalNestedMessage(TestAllTypes.Types.NestedMessage.DefaultInstance); - Assert.IsTrue(builder.HasOptionalNestedMessage); - Assert.IsTrue(builder.Build().HasOptionalNestedMessage); - } - - [Test] - public void TestSerializeAndParse() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - builder.SetOptionalInt32(1234); - builder.SetOptionalString("hello"); - builder.SetOptionalNestedMessage(TestAllTypes.Types.NestedMessage.DefaultInstance); - builder.SetOneofUint32(0U); - ByteString data = builder.Build().ToByteString(); - - TestAllTypes message = TestAllTypes.ParseFrom(data); - Assert.AreEqual(1234, message.OptionalInt32); - Assert.AreEqual("hello", message.OptionalString); - Assert.AreEqual(ByteString.Empty, message.OptionalBytes); - Assert.AreEqual(TestAllTypes.Types.NestedEnum.FOO, message.OptionalNestedEnum); - Assert.IsTrue(message.HasOptionalNestedMessage); - Assert.AreEqual(0, message.OptionalNestedMessage.Bb); - Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, message.OneofFieldCase); - } - } -} diff --git a/csharp/src/ProtocolBuffers.Test/GeneratedBuilderTest.cs b/csharp/src/ProtocolBuffers.Test/GeneratedBuilderTest.cs deleted file mode 100644 index 257f5001..00000000 --- a/csharp/src/ProtocolBuffers.Test/GeneratedBuilderTest.cs +++ /dev/null @@ -1,102 +0,0 @@ -using System; -using System.Collections.Generic; -using Google.ProtocolBuffers.TestProtos; -using NUnit.Framework; - -namespace Google.ProtocolBuffers -{ - public class GeneratedBuilderTest - { - class OneTimeEnumerator : IEnumerable - { - readonly T _item; - bool _enumerated; - public OneTimeEnumerator(T item) - { - _item = item; - } - public IEnumerator GetEnumerator() - { - Assert.IsFalse(_enumerated); - _enumerated = true; - yield return _item; - } - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - } - - [Test] - public void DoesNotEnumerateTwiceForMessageList() - { - TestAllTypes.Builder b = new TestAllTypes.Builder(); - b.AddRangeRepeatedForeignMessage(new OneTimeEnumerator(ForeignMessage.DefaultInstance)); - } - - [Test] - public void DoesNotEnumerateTwiceForPrimitiveList() - { - TestAllTypes.Builder b = new TestAllTypes.Builder(); - b.AddRangeRepeatedInt32(new OneTimeEnumerator(1)); - } - - [Test] - public void DoesNotEnumerateTwiceForStringList() - { - TestAllTypes.Builder b = new TestAllTypes.Builder(); - b.AddRangeRepeatedString(new OneTimeEnumerator("test")); - } - - [Test] - public void DoesNotEnumerateTwiceForEnumList() - { - TestAllTypes.Builder b = new TestAllTypes.Builder(); - b.AddRangeRepeatedForeignEnum(new OneTimeEnumerator(ForeignEnum.FOREIGN_BAR)); - } - - [Test] - public void DoesNotAddNullToMessageListByAddRange() - { - TestAllTypes.Builder b = new TestAllTypes.Builder(); - Assert.Throws(() => b.AddRangeRepeatedForeignMessage(new ForeignMessage[] { null })); - } - - [Test] - public void DoesNotAddNullToMessageListByAdd() - { - TestAllTypes.Builder b = new TestAllTypes.Builder(); - Assert.Throws(() => b.AddRepeatedForeignMessage((ForeignMessage)null)); - } - - [Test] - public void DoesNotAddNullToMessageListBySet() - { - TestAllTypes.Builder b = new TestAllTypes.Builder(); - b.AddRepeatedForeignMessage(ForeignMessage.DefaultInstance); - Assert.Throws(() => b.SetRepeatedForeignMessage(0, (ForeignMessage)null)); - } - - [Test] - public void DoesNotAddNullToStringListByAddRange() - { - TestAllTypes.Builder b = new TestAllTypes.Builder(); - Assert.Throws(() => b.AddRangeRepeatedString(new String[] { null })); - } - - [Test] - public void DoesNotAddNullToStringListByAdd() - { - TestAllTypes.Builder b = new TestAllTypes.Builder(); - Assert.Throws(() => b.AddRepeatedString(null)); - } - - [Test] - public void DoesNotAddNullToStringListBySet() - { - TestAllTypes.Builder b = new TestAllTypes.Builder(); - b.AddRepeatedString("one"); - Assert.Throws(() => b.SetRepeatedString(0, null)); - } - } -} diff --git a/csharp/src/ProtocolBuffers.Test/GeneratedMessageTest.cs b/csharp/src/ProtocolBuffers.Test/GeneratedMessageTest.cs index 4f669449..c5564060 100644 --- a/csharp/src/ProtocolBuffers.Test/GeneratedMessageTest.cs +++ b/csharp/src/ProtocolBuffers.Test/GeneratedMessageTest.cs @@ -1,776 +1,153 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; +using System; using System.Collections.Generic; -using Google.ProtocolBuffers.Descriptors; -using Google.ProtocolBuffers.Collections; -using Google.ProtocolBuffers.TestProtos; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Google.Protobuf.TestProtos; using NUnit.Framework; -namespace Google.ProtocolBuffers +namespace Google.Protobuf { + /// + /// Tests around the generated TestAllTypes message. + /// public class GeneratedMessageTest { - private readonly ReflectionTester reflectionTester; - private readonly ReflectionTester extensionsReflectionTester; - - public GeneratedMessageTest() - { - reflectionTester = ReflectionTester.CreateTestAllTypesInstance(); - extensionsReflectionTester = ReflectionTester.CreateTestAllExtensionsInstance(); - } - - [Test] - public void RepeatedAddPrimitiveBeforeBuild() - { - TestAllTypes message = new TestAllTypes.Builder {RepeatedInt32List = {1, 2, 3}}.Build(); - TestUtil.AssertEqual(new int[] {1, 2, 3}, message.RepeatedInt32List); - } - - [Test] - public void AddPrimitiveFailsAfterBuild() - { - TestAllTypes.Builder builder = new TestAllTypes.Builder(); - IList list = builder.RepeatedInt32List; - list.Add(1); // Fine - builder.Build(); - - Assert.Throws(() => list.Add(2)); - } - - [Test] - public void RepeatedAddMessageBeforeBuild() - { - TestAllTypes message = new TestAllTypes.Builder - { - RepeatedNestedMessageList = - {new TestAllTypes.Types.NestedMessage.Builder {Bb = 10}.Build()} - }.Build(); - Assert.AreEqual(1, message.RepeatedNestedMessageCount); - Assert.AreEqual(10, message.RepeatedNestedMessageList[0].Bb); - } - - [Test] - public void AddMessageFailsAfterBuild() - { - TestAllTypes.Builder builder = new TestAllTypes.Builder(); - IList list = builder.RepeatedNestedMessageList; - builder.Build(); - - Assert.Throws(() => list.Add(new TestAllTypes.Types.NestedMessage.Builder { Bb = 10 }.Build())); - } - - [Test] - public void DefaultInstance() - { - Assert.AreSame(TestAllTypes.DefaultInstance, TestAllTypes.DefaultInstance.DefaultInstanceForType); - Assert.AreSame(TestAllTypes.DefaultInstance, TestAllTypes.CreateBuilder().DefaultInstanceForType); - } - - [Test] - public void Accessors() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - TestUtil.SetAllFields(builder); - TestAllTypes message = builder.Build(); - TestUtil.AssertAllFieldsSet(message); - } - - [Test] - public void SettersRejectNull() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - Assert.Throws(() => builder.SetOptionalString(null)); - Assert.Throws(() => builder.SetOptionalBytes(null)); - Assert.Throws( - () => builder.SetOptionalNestedMessage((TestAllTypes.Types.NestedMessage) null)); - Assert.Throws( - () => builder.SetOptionalNestedMessage((TestAllTypes.Types.NestedMessage.Builder) null)); - Assert.Throws(() => builder.AddRepeatedString(null)); - Assert.Throws(() => builder.AddRepeatedBytes(null)); - Assert.Throws( - () => builder.AddRepeatedNestedMessage((TestAllTypes.Types.NestedMessage) null)); - Assert.Throws( - () => builder.AddRepeatedNestedMessage((TestAllTypes.Types.NestedMessage.Builder) null)); - } - - [Test] - public void RepeatedSetters() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - TestUtil.SetAllFields(builder); - TestUtil.ModifyRepeatedFields(builder); - TestAllTypes message = builder.Build(); - TestUtil.AssertRepeatedFieldsModified(message); - } - - [Test] - public void RepeatedAppend() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - - builder.AddRangeRepeatedInt32(new int[] {1, 2, 3, 4}); - builder.AddRangeRepeatedForeignEnum((new ForeignEnum[] {ForeignEnum.FOREIGN_BAZ})); - - ForeignMessage foreignMessage = ForeignMessage.CreateBuilder().SetC(12).Build(); - builder.AddRangeRepeatedForeignMessage(new ForeignMessage[] {foreignMessage}); - - TestAllTypes message = builder.Build(); - TestUtil.AssertEqual(message.RepeatedInt32List, new int[] {1, 2, 3, 4}); - TestUtil.AssertEqual(message.RepeatedForeignEnumList, new ForeignEnum[] {ForeignEnum.FOREIGN_BAZ}); - Assert.AreEqual(1, message.RepeatedForeignMessageCount); - Assert.AreEqual(12, message.GetRepeatedForeignMessage(0).C); - } - - [Test] - public void RepeatedAppendRejectsNull() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - - ForeignMessage foreignMessage = ForeignMessage.CreateBuilder().SetC(12).Build(); - Assert.Throws( - () => builder.AddRangeRepeatedForeignMessage(new[] {foreignMessage, null})); - Assert.Throws(() => builder.AddRangeRepeatedForeignMessage(null)); - Assert.Throws(() => builder.AddRangeRepeatedForeignEnum(null)); - Assert.Throws(() => builder.AddRangeRepeatedString(new[] {"one", null})); - Assert.Throws( - () => builder.AddRangeRepeatedBytes(new[] {TestUtil.ToBytes("one"), null})); - } - - [Test] - public void SettingForeignMessageUsingBuilder() - { - TestAllTypes message = TestAllTypes.CreateBuilder() - // Pass builder for foreign message instance. - .SetOptionalForeignMessage(ForeignMessage.CreateBuilder().SetC(123)) - .Build(); - TestAllTypes expectedMessage = TestAllTypes.CreateBuilder() - // Create expected version passing foreign message instance explicitly. - .SetOptionalForeignMessage(ForeignMessage.CreateBuilder().SetC(123).Build()) - .Build(); - Assert.AreEqual(expectedMessage, message); - } - - [Test] - public void SettingRepeatedForeignMessageUsingBuilder() - { - TestAllTypes message = TestAllTypes.CreateBuilder() - // Pass builder for foreign message instance. - .AddRepeatedForeignMessage(ForeignMessage.CreateBuilder().SetC(456)) - .Build(); - TestAllTypes expectedMessage = TestAllTypes.CreateBuilder() - // Create expected version passing foreign message instance explicitly. - .AddRepeatedForeignMessage(ForeignMessage.CreateBuilder().SetC(456).Build()) - .Build(); - Assert.AreEqual(expectedMessage, message); - } - - [Test] - public void SettingRepeatedValuesUsingRangeInCollectionInitializer() - { - int[] values = {1, 2, 3}; - TestAllTypes message = new TestAllTypes.Builder - { - RepeatedSint32List = {values} - }.Build(); - Assert.IsTrue(Lists.Equals(values, message.RepeatedSint32List)); - } - - [Test] - public void SettingRepeatedValuesUsingIndividualValuesInCollectionInitializer() - { - TestAllTypes message = new TestAllTypes.Builder - { - RepeatedSint32List = {6, 7} - }.Build(); - Assert.IsTrue(Lists.Equals(new int[] {6, 7}, message.RepeatedSint32List)); - } - - [Test] - public void Defaults() - { - TestUtil.AssertClear(TestAllTypes.DefaultInstance); - TestUtil.AssertClear(TestAllTypes.CreateBuilder().Build()); - - Assert.AreEqual("\u1234", TestExtremeDefaultValues.DefaultInstance.Utf8String); - } - - [Test] - public void ReflectionGetters() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - TestUtil.SetAllFields(builder); - TestAllTypes message = builder.Build(); - reflectionTester.AssertAllFieldsSetViaReflection(message); - } - - [Test] - public void ReflectionSetters() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - reflectionTester.SetAllFieldsViaReflection(builder); - TestAllTypes message = builder.Build(); - TestUtil.AssertAllFieldsSet(message); - } - - [Test] - public void ReflectionClear() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - reflectionTester.SetAllFieldsViaReflection(builder); - reflectionTester.ClearAllFieldsViaReflection(builder); - TestAllTypes message = builder.Build(); - TestUtil.AssertClear(message); - } - - [Test] - public void ReflectionSettersRejectNull() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - reflectionTester.AssertReflectionSettersRejectNull(builder); - } - - [Test] - public void ReflectionRepeatedSetters() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - reflectionTester.SetAllFieldsViaReflection(builder); - reflectionTester.ModifyRepeatedFieldsViaReflection(builder); - TestAllTypes message = builder.Build(); - TestUtil.AssertRepeatedFieldsModified(message); - } - - [Test] - public void TestReflectionRepeatedSettersRejectNull() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - reflectionTester.AssertReflectionRepeatedSettersRejectNull(builder); - } - - [Test] - public void ReflectionDefaults() - { - TestUtil.TestInMultipleCultures(() => - { - reflectionTester.AssertClearViaReflection( - TestAllTypes.DefaultInstance); - reflectionTester.AssertClearViaReflection( - TestAllTypes.CreateBuilder().Build()); - }); - } - - [Test] - public void ReflectionGetOneof() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - reflectionTester.SetAllFieldsViaReflection(builder); - Descriptors.OneofDescriptor oneof = TestAllTypes.Descriptor.Oneofs[0]; - Descriptors.FieldDescriptor field = TestAllTypes.Descriptor.FindFieldByName("oneof_bytes"); - Assert.AreSame(field, builder.OneofFieldDescriptor(oneof)); - } - - [Test] - public void ReflectionClearOneof() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - reflectionTester.SetAllFieldsViaReflection(builder); - OneofDescriptor oneof = TestAllTypes.Descriptor.Oneofs[0]; - FieldDescriptor field = TestAllTypes.Descriptor.FindFieldByName("oneof_bytes"); - - Assert.IsTrue(builder.HasOneof(oneof)); - Assert.IsTrue(builder.HasField(field)); - builder.ClearOneof(oneof); - Assert.IsFalse(builder.HasOneof(oneof)); - Assert.IsFalse(builder.HasField(field)); - } - - // ================================================================= - // Extensions. - - [Test] - public void ExtensionAccessors() - { - TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder(); - TestUtil.SetAllExtensions(builder); - TestAllExtensions message = builder.Build(); - TestUtil.AssertAllExtensionsSet(message); - } - - [Test] - public void ExtensionRepeatedSetters() - { - TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder(); - TestUtil.SetAllExtensions(builder); - TestUtil.ModifyRepeatedExtensions(builder); - TestAllExtensions message = builder.Build(); - TestUtil.AssertRepeatedExtensionsModified(message); - } - - [Test] - public void ExtensionDefaults() - { - TestUtil.AssertExtensionsClear(TestAllExtensions.DefaultInstance); - TestUtil.AssertExtensionsClear(TestAllExtensions.CreateBuilder().Build()); - } - - [Test] - public void ExtensionReflectionGetters() - { - TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder(); - TestUtil.SetAllExtensions(builder); - TestAllExtensions message = builder.Build(); - extensionsReflectionTester.AssertAllFieldsSetViaReflection(message); - } - - [Test] - public void ExtensionReflectionSetters() - { - TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder(); - extensionsReflectionTester.SetAllFieldsViaReflection(builder); - TestAllExtensions message = builder.Build(); - TestUtil.AssertAllExtensionsSet(message); - } - [Test] - public void ExtensionReflectionSettersRejectNull() - { - TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder(); - extensionsReflectionTester.AssertReflectionSettersRejectNull(builder); - } - - [Test] - public void ExtensionReflectionRepeatedSetters() - { - TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder(); - extensionsReflectionTester.SetAllFieldsViaReflection(builder); - extensionsReflectionTester.ModifyRepeatedFieldsViaReflection(builder); - TestAllExtensions message = builder.Build(); - TestUtil.AssertRepeatedExtensionsModified(message); - } - - [Test] - public void ExtensionReflectionRepeatedSettersRejectNull() - { - TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder(); - extensionsReflectionTester.AssertReflectionRepeatedSettersRejectNull(builder); - } - - [Test] - public void ExtensionReflectionDefaults() - { - TestUtil.TestInMultipleCultures(() => - { - extensionsReflectionTester.AssertClearViaReflection( - TestAllExtensions.DefaultInstance); - extensionsReflectionTester.AssertClearViaReflection( - TestAllExtensions.CreateBuilder().Build()); - }); - } - - [Test] - public void ClearExtension() - { - // ClearExtension() is not actually used in TestUtil, so try it manually. - Assert.IsFalse(TestAllExtensions.CreateBuilder() - .SetExtension(Unittest.OptionalInt32Extension, 1) - .ClearExtension(Unittest.OptionalInt32Extension) - .HasExtension(Unittest.OptionalInt32Extension)); - Assert.AreEqual(0, TestAllExtensions.CreateBuilder() - .AddExtension(Unittest.RepeatedInt32Extension, 1) - .ClearExtension(Unittest.RepeatedInt32Extension) - .GetExtensionCount(Unittest.RepeatedInt32Extension)); - } - - [Test] - public void ExtensionMergeFrom() - { - TestAllExtensions original = TestAllExtensions.CreateBuilder() - .SetExtension(Unittest.OptionalInt32Extension, 1).Build(); - TestAllExtensions merged = - TestAllExtensions.CreateBuilder().MergeFrom(original).Build(); - Assert.IsTrue((merged.HasExtension(Unittest.OptionalInt32Extension))); - Assert.AreEqual(1, (int) merged.GetExtension(Unittest.OptionalInt32Extension)); - } - - /* Removed multiple files option for the moment - [Test] - public void MultipleFilesOption() { - // We mostly just want to check that things compile. - MessageWithNoOuter message = MessageWithNoOuter.CreateBuilder() - .SetNested(MessageWithNoOuter.Types.NestedMessage.CreateBuilder().SetI(1)) - .AddForeign(TestAllTypes.CreateBuilder().SetOptionalInt32(1)) - .SetNestedEnum(MessageWithNoOuter.Types.NestedEnum.BAZ) - .SetForeignEnum(EnumWithNoOuter.BAR) - .Build(); - Assert.AreEqual(message, MessageWithNoOuter.ParseFrom(message.ToByteString())); - - Assert.AreEqual(MultiFileProto.DescriptorProtoFile, MessageWithNoOuter.DescriptorProtoFile.File); - - FieldDescriptor field = MessageWithNoOuter.DescriptorProtoFile.FindDescriptor("foreign_enum"); - Assert.AreEqual(MultiFileProto.DescriptorProtoFile.FindTypeByName("EnumWithNoOuter") - .FindValueByNumber((int)EnumWithNoOuter.BAR), message[field]); - - Assert.AreEqual(MultiFileProto.DescriptorProtoFile, ServiceWithNoOuter.DescriptorProtoFile.File); - - Assert.IsFalse(TestAllExtensions.DefaultInstance.HasExtension(MultiFileProto.ExtensionWithOuter)); - }*/ - - [Test] - public void OptionalFieldWithRequiredSubfieldsOptimizedForSize() - { - TestOptionalOptimizedForSize message = TestOptionalOptimizedForSize.DefaultInstance; - Assert.IsTrue(message.IsInitialized); - - message = TestOptionalOptimizedForSize.CreateBuilder().SetO( - TestRequiredOptimizedForSize.CreateBuilder().BuildPartial() - ).BuildPartial(); - Assert.IsFalse(message.IsInitialized); - - message = TestOptionalOptimizedForSize.CreateBuilder().SetO( - TestRequiredOptimizedForSize.CreateBuilder().SetX(5).BuildPartial() - ).BuildPartial(); - Assert.IsTrue(message.IsInitialized); - } - - [Test] - public void OptimizedForSizeMergeUsesAllFieldsFromTarget() - { - TestOptimizedForSize withFieldSet = new TestOptimizedForSize.Builder {I = 10}.Build(); - TestOptimizedForSize.Builder builder = new TestOptimizedForSize.Builder(); - builder.MergeFrom(withFieldSet); - TestOptimizedForSize built = builder.Build(); - Assert.AreEqual(10, built.I); - } - - [Test] - public void UninitializedExtensionInOptimizedForSizeMakesMessageUninitialized() - { - TestOptimizedForSize.Builder builder = new TestOptimizedForSize.Builder(); - builder.SetExtension(TestOptimizedForSize.TestExtension2, - new TestRequiredOptimizedForSize.Builder().BuildPartial()); - Assert.IsFalse(builder.IsInitialized); - Assert.IsFalse(builder.BuildPartial().IsInitialized); - - builder = new TestOptimizedForSize.Builder(); - builder.SetExtension(TestOptimizedForSize.TestExtension2, - new TestRequiredOptimizedForSize.Builder {X = 10}.BuildPartial()); - Assert.IsTrue(builder.IsInitialized); - Assert.IsTrue(builder.BuildPartial().IsInitialized); - } - - [Test] - public void ToBuilder() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - TestUtil.SetAllFields(builder); - TestAllTypes message = builder.Build(); - TestUtil.AssertAllFieldsSet(message.ToBuilder().Build()); - } - - [Test] - public void FieldConstantValues() - { - Assert.AreEqual(TestAllTypes.Types.NestedMessage.BbFieldNumber, 1); - Assert.AreEqual(TestAllTypes.OptionalInt32FieldNumber, 1); - Assert.AreEqual(TestAllTypes.OptionalGroupFieldNumber, 16); - Assert.AreEqual(TestAllTypes.OptionalNestedMessageFieldNumber, 18); - Assert.AreEqual(TestAllTypes.OptionalNestedEnumFieldNumber, 21); - Assert.AreEqual(TestAllTypes.RepeatedInt32FieldNumber, 31); - Assert.AreEqual(TestAllTypes.RepeatedGroupFieldNumber, 46); - Assert.AreEqual(TestAllTypes.RepeatedNestedMessageFieldNumber, 48); - Assert.AreEqual(TestAllTypes.RepeatedNestedEnumFieldNumber, 51); - } - - [Test] - public void ExtensionConstantValues() - { - Assert.AreEqual(TestRequired.SingleFieldNumber, 1000); - Assert.AreEqual(TestRequired.MultiFieldNumber, 1001); - Assert.AreEqual(Unittest.OptionalInt32ExtensionFieldNumber, 1); - Assert.AreEqual(Unittest.OptionalGroupExtensionFieldNumber, 16); - Assert.AreEqual(Unittest.OptionalNestedMessageExtensionFieldNumber, 18); - Assert.AreEqual(Unittest.OptionalNestedEnumExtensionFieldNumber, 21); - Assert.AreEqual(Unittest.RepeatedInt32ExtensionFieldNumber, 31); - Assert.AreEqual(Unittest.RepeatedGroupExtensionFieldNumber, 46); - Assert.AreEqual(Unittest.RepeatedNestedMessageExtensionFieldNumber, 48); - Assert.AreEqual(Unittest.RepeatedNestedEnumExtensionFieldNumber, 51); - } - - [Test] - public void EmptyPackedValue() - { - TestPackedTypes empty = new TestPackedTypes.Builder().Build(); - Assert.AreEqual(0, empty.SerializedSize); - } - - // oneof tests - [Test] - public void TestOneofEnumCase() - { - TestOneof2 message = TestOneof2.CreateBuilder() - .SetFooInt(123).SetFooString("foo").SetFooCord("bar").Build(); - TestUtil.AssertAtMostOneFieldSetOneof(message); - } - - [Test] - public void TestClearOneof() - { - TestOneof2.Builder builder = TestOneof2.CreateBuilder().SetFooInt(123); - Assert.AreEqual(TestOneof2.FooOneofCase.FooInt, builder.FooCase); - builder.ClearFoo(); - Assert.AreEqual(TestOneof2.FooOneofCase.None, builder.FooCase); - } - - [Test] - public void TestSetOneofClearsOthers() - { - TestOneof2.Builder builder = TestOneof2.CreateBuilder(); - TestOneof2 message = - builder.SetFooInt(123).SetFooString("foo").Build(); - Assert.IsTrue(message.HasFooString); - TestUtil.AssertAtMostOneFieldSetOneof(message); - - message = builder.SetFooCord("bar").Build(); - Assert.IsTrue(message.HasFooCord); - TestUtil.AssertAtMostOneFieldSetOneof(message); - - message = builder.SetFooStringPiece("baz").Build(); - Assert.IsTrue(message.HasFooStringPiece); - TestUtil.AssertAtMostOneFieldSetOneof(message); - - message = builder.SetFooBytes(TestUtil.ToBytes("qux")).Build(); - Assert.IsTrue(message.HasFooBytes); - TestUtil.AssertAtMostOneFieldSetOneof(message); - - message = builder.SetFooEnum(TestOneof2.Types.NestedEnum.FOO).Build(); - Assert.IsTrue(message.HasFooEnum); - TestUtil.AssertAtMostOneFieldSetOneof(message); - - message = builder.SetFooMessage( - TestOneof2.Types.NestedMessage.CreateBuilder().SetQuxInt(234).Build()).Build(); - Assert.IsTrue(message.HasFooMessage); - TestUtil.AssertAtMostOneFieldSetOneof(message); - - message = builder.SetFooInt(123).Build(); - Assert.IsTrue(message.HasFooInt); - TestUtil.AssertAtMostOneFieldSetOneof(message); - } - - [Test] - public void TestOneofTypes_Primitive() - { - TestOneof2.Builder builder = TestOneof2.CreateBuilder(); - Assert.AreEqual(builder.FooInt, 0); - Assert.IsFalse(builder.HasFooInt); - Assert.IsTrue(builder.SetFooInt(123).HasFooInt); - Assert.AreEqual(builder.FooInt, 123); - TestOneof2 message = builder.BuildPartial(); - Assert.IsTrue(message.HasFooInt); - Assert.AreEqual(message.FooInt, 123); - - Assert.IsFalse(builder.ClearFooInt().HasFooInt); - TestOneof2 message2 = builder.Build(); - Assert.IsFalse(message2.HasFooInt); - Assert.AreEqual(message2.FooInt, 0); - } - - [Test] - public void TestOneofTypes_Enum() - { - TestOneof2.Builder builder = TestOneof2.CreateBuilder(); - Assert.AreEqual(builder.FooEnum, TestOneof2.Types.NestedEnum.FOO); - Assert.IsTrue(builder.SetFooEnum(TestOneof2.Types.NestedEnum.BAR).HasFooEnum); - Assert.AreEqual(builder.FooEnum, TestOneof2.Types.NestedEnum.BAR); - TestOneof2 message = builder.BuildPartial(); - Assert.IsTrue(message.HasFooEnum); - Assert.AreEqual(message.FooEnum, TestOneof2.Types.NestedEnum.BAR); - - Assert.IsFalse(builder.ClearFooEnum().HasFooEnum); - TestOneof2 message2 = builder.Build(); - Assert.IsFalse(message2.HasFooEnum); - Assert.AreEqual(message2.FooEnum, TestOneof2.Types.NestedEnum.FOO); - } - - [Test] - public void TestOneofTypes_String() - { - TestOneof2.Builder builder = TestOneof2.CreateBuilder(); - Assert.AreEqual(builder.FooString, ""); - Assert.IsTrue(builder.SetFooString("foo").HasFooString); - Assert.AreEqual(builder.FooString, "foo"); - TestOneof2 message = builder.BuildPartial(); - Assert.IsTrue(message.HasFooString); - Assert.AreEqual(message.FooString, "foo"); - - Assert.IsFalse(builder.ClearFooString().HasFooString); - TestOneof2 message2 = builder.Build(); - Assert.IsFalse(message2.HasFooString); - Assert.AreEqual(message2.FooString, ""); - - builder.SetFooInt(123); - Assert.AreEqual(builder.FooString, ""); - Assert.AreEqual(builder.FooInt, 123); - message = builder.Build(); - Assert.AreEqual(message.FooString, ""); - Assert.AreEqual(message.FooInt, 123); - } - - [Test] - public void TestOneofTypes_Message() - { - TestOneof2.Builder builder = TestOneof2.CreateBuilder(); - Assert.AreEqual(builder.FooMessage.QuxInt, 0); - builder.SetFooMessage(TestOneof2.Types.NestedMessage.CreateBuilder().SetQuxInt(234).Build()); - Assert.IsTrue(builder.HasFooMessage); - Assert.AreEqual(builder.FooMessage.QuxInt, 234); - TestOneof2 message = builder.BuildPartial(); - Assert.IsTrue(message.HasFooMessage); - Assert.AreEqual(message.FooMessage.QuxInt, 234); - - Assert.IsFalse(builder.ClearFooMessage().HasFooMessage); - message = builder.Build(); - Assert.IsFalse(message.HasFooMessage); - Assert.AreEqual(message.FooMessage.QuxInt, 0); - - builder = TestOneof2.CreateBuilder(); - Assert.IsFalse(builder.HasFooMessage); - builder.SetFooMessage(TestOneof2.Types.NestedMessage.CreateBuilder().SetQuxInt(123)); - Assert.IsTrue(builder.HasFooMessage); - Assert.AreEqual(builder.FooMessage.QuxInt, 123); - message = builder.Build(); - Assert.IsTrue(message.HasFooMessage); - Assert.AreEqual(message.FooMessage.QuxInt, 123); - } - - [Test] - public void TestOneofMerge_Primitive() - { - TestOneof2.Builder builder = TestOneof2.CreateBuilder(); - TestOneof2 message = builder.SetFooInt(123).Build(); - TestOneof2 message2 = TestOneof2.CreateBuilder().MergeFrom(message).Build(); - Assert.IsTrue(message2.HasFooInt); - Assert.AreEqual(message2.FooInt, 123); - } - - [Test] - public void TestOneofMerge_String() - { - TestOneof2.Builder builder = TestOneof2.CreateBuilder(); - TestOneof2 message = builder.SetFooString("foo").Build(); - TestOneof2 message2 = TestOneof2.CreateBuilder().MergeFrom(message).Build(); - Assert.IsTrue(message2.HasFooString); - Assert.AreEqual(message2.FooString, "foo"); - } - - [Test] - public void TestOneofMerge_Enum() - { - TestOneof2.Builder builder = TestOneof2.CreateBuilder(); - TestOneof2 message = builder.SetFooEnum(TestOneof2.Types.NestedEnum.BAR).Build(); - TestOneof2 message2 = TestOneof2.CreateBuilder().MergeFrom(message).Build(); - Assert.IsTrue(message2.HasFooEnum); - Assert.AreEqual(message2.FooEnum, TestOneof2.Types.NestedEnum.BAR); - } - - public void TestOneofMerge_message() - { - TestOneof2.Builder builder = TestOneof2.CreateBuilder(); - TestOneof2 message = builder.SetFooMessage( - TestOneof2.Types.NestedMessage.CreateBuilder().SetQuxInt(234).Build()).Build(); - TestOneof2 message2 = TestOneof2.CreateBuilder().MergeFrom(message).Build(); - Assert.IsTrue(message2.HasFooMessage); - Assert.AreEqual(message2.FooMessage.QuxInt, 234); - } - - [Test] - public void TestOneofMergeMixed() - { - TestOneof2.Builder builder = TestOneof2.CreateBuilder(); - TestOneof2 message = builder.SetFooEnum(TestOneof2.Types.NestedEnum.BAR).Build(); - TestOneof2 message2 = - TestOneof2.CreateBuilder().SetFooString("foo").MergeFrom(message).Build(); - Assert.IsFalse(message2.HasFooString); - Assert.IsTrue(message2.HasFooEnum); - Assert.AreEqual(message2.FooEnum, TestOneof2.Types.NestedEnum.BAR); - } - - [Test] - public void TestOneofSerialization_Primitive() - { - TestOneof2.Builder builder = TestOneof2.CreateBuilder(); - TestOneof2 message = builder.SetFooInt(123).Build(); - ByteString serialized = message.ToByteString(); - TestOneof2 message2 = TestOneof2.ParseFrom(serialized); - Assert.IsTrue(message2.HasFooInt); - Assert.AreEqual(message2.FooInt, 123); - } - - [Test] - public void TestOneofSerialization_String() - { - TestOneof2.Builder builder = TestOneof2.CreateBuilder(); - TestOneof2 message = builder.SetFooString("foo").Build(); - ByteString serialized = message.ToByteString(); - TestOneof2 message2 = TestOneof2.ParseFrom(serialized); - Assert.IsTrue(message2.HasFooString); - Assert.AreEqual(message2.FooString, "foo"); - } - - [Test] - public void TestOneofSerialization_Enum() - { - TestOneof2.Builder builder = TestOneof2.CreateBuilder(); - TestOneof2 message = builder.SetFooEnum(TestOneof2.Types.NestedEnum.BAR).Build(); - ByteString serialized = message.ToByteString(); - TestOneof2 message2 = TestOneof2.ParseFrom(serialized); - Assert.IsTrue(message2.HasFooEnum); - Assert.AreEqual(message2.FooEnum, TestOneof2.Types.NestedEnum.BAR); - } - - [Test] - public void TestOneofSerialization_Message() - { - TestOneof2.Builder builder = TestOneof2.CreateBuilder(); - TestOneof2 message = builder.SetFooMessage( - TestOneof2.Types.NestedMessage.CreateBuilder().SetQuxInt(234).Build()).Build(); - ByteString serialized = message.ToByteString(); - TestOneof2 message2 = TestOneof2.ParseFrom(serialized); - Assert.IsTrue(message2.HasFooMessage); - Assert.AreEqual(message2.FooMessage.QuxInt, 234); + public void DefaultValues() + { + // Single fields + var message = new TestAllTypes(); + Assert.AreEqual(false, message.SingleBool); + Assert.AreEqual(ByteString.Empty, message.SingleBytes); + Assert.AreEqual(0.0, message.SingleDouble); + Assert.AreEqual(0, message.SingleFixed32); + Assert.AreEqual(0L, message.SingleFixed64); + Assert.AreEqual(0.0f, message.SingleFloat); + Assert.AreEqual(ForeignEnum.FOREIGN_UNSPECIFIED, message.SingleForeignEnum); + Assert.IsNull(message.SingleForeignMessage); + Assert.AreEqual(ImportEnum.IMPORT_ENUM_UNSPECIFIED, message.SingleImportEnum); + Assert.IsNull(message.SingleImportMessage); + Assert.AreEqual(0, message.SingleInt32); + Assert.AreEqual(0L, message.SingleInt64); + Assert.AreEqual(TestAllTypes.Types.NestedEnum.NESTED_ENUM_UNSPECIFIED, message.SingleNestedEnum); + Assert.IsNull(message.SingleNestedMessage); + Assert.IsNull(message.SinglePublicImportMessage); + Assert.AreEqual(0, message.SingleSfixed32); + Assert.AreEqual(0L, message.SingleSfixed64); + Assert.AreEqual(0, message.SingleSint32); + Assert.AreEqual(0L, message.SingleSint64); + Assert.AreEqual("", message.SingleString); + Assert.AreEqual(0U, message.SingleUint32); + Assert.AreEqual(0UL, message.SingleUint64); + + // Repeated fields + Assert.AreEqual(0, message.RepeatedBool.Count); + Assert.AreEqual(0, message.RepeatedBytes.Count); + Assert.AreEqual(0, message.RepeatedDouble.Count); + Assert.AreEqual(0, message.RepeatedFixed32.Count); + Assert.AreEqual(0, message.RepeatedFixed64.Count); + Assert.AreEqual(0, message.RepeatedFloat.Count); + Assert.AreEqual(0, message.RepeatedForeignEnum.Count); + Assert.AreEqual(0, message.RepeatedForeignMessage.Count); + Assert.AreEqual(0, message.RepeatedImportEnum.Count); + Assert.AreEqual(0, message.RepeatedImportMessage.Count); + Assert.AreEqual(0, message.RepeatedNestedEnum.Count); + Assert.AreEqual(0, message.RepeatedNestedMessage.Count); + Assert.AreEqual(0, message.RepeatedPublicImportMessage.Count); + Assert.AreEqual(0, message.RepeatedSfixed32.Count); + Assert.AreEqual(0, message.RepeatedSfixed64.Count); + Assert.AreEqual(0, message.RepeatedSint32.Count); + Assert.AreEqual(0, message.RepeatedSint64.Count); + Assert.AreEqual(0, message.RepeatedString.Count); + Assert.AreEqual(0, message.RepeatedUint32.Count); + Assert.AreEqual(0, message.RepeatedUint64.Count); + + // Oneof fields + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.None, message.OneofFieldCase); + Assert.AreEqual(0, message.OneofUint32); + Assert.AreEqual("", message.OneofString); + Assert.AreEqual(ByteString.Empty, message.OneofBytes); + Assert.IsNull(message.OneofNestedMessage); + } + + [Test] + public void RoundTrip_Empty() + { + var message = new TestAllTypes(); + // Without setting any values, there's nothing to write. + byte[] bytes = message.ToByteArray(); + Assert.AreEqual(0, bytes.Length); + TestAllTypes parsed = TestAllTypes.Parser.ParseFrom(bytes); + Assert.AreEqual(message, parsed); + } + + [Test] + public void RoundTrip_SingleValues() + { + var message = new TestAllTypes + { + SingleBool = true, + SingleBytes = ByteString.CopyFrom(new byte[] { 1, 2, 3, 4 }), + SingleDouble = 23.5, + SingleFixed32 = 23, + SingleFixed64 = 1234567890123, + SingleFloat = 12.25f, + SingleForeignEnum = ForeignEnum.FOREIGN_BAR, + SingleForeignMessage = new ForeignMessage { C = 10 }, + SingleImportEnum = ImportEnum.IMPORT_BAZ, + SingleImportMessage = new ImportMessage { D = 20 }, + SingleInt32 = 100, + SingleInt64 = 3210987654321, + SingleNestedEnum = TestAllTypes.Types.NestedEnum.FOO, + SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 35 }, + SinglePublicImportMessage = new PublicImportMessage { E = 54 }, + SingleSfixed32 = -123, + SingleSfixed64 = -12345678901234, + SingleSint32 = -456, + SingleSint64 = -12345678901235, + SingleString = "test", + SingleUint32 = uint.MaxValue, + SingleUint64 = ulong.MaxValue + }; + + byte[] bytes = message.ToByteArray(); + TestAllTypes parsed = TestAllTypes.Parser.ParseFrom(bytes); + Assert.AreEqual(message, parsed); + } + + [Test] + public void RoundTrip_RepeatedValues() + { + var message = new TestAllTypes + { + RepeatedBool = { true, false }, + RepeatedBytes = { ByteString.CopyFrom(new byte[] { 1, 2, 3, 4 }), ByteString.CopyFrom(new byte[] { 5, 6 }) }, + RepeatedDouble = { -12.25, 23.5 }, + RepeatedFixed32 = { uint.MaxValue, 23 }, + RepeatedFixed64 = { ulong.MaxValue, 1234567890123 }, + RepeatedFloat = { 100f, 12.25f }, + RepeatedForeignEnum = { ForeignEnum.FOREIGN_FOO, ForeignEnum.FOREIGN_BAR }, + RepeatedForeignMessage = { new ForeignMessage(), new ForeignMessage { C = 10 } }, + RepeatedImportEnum = { ImportEnum.IMPORT_BAZ, ImportEnum.IMPORT_ENUM_UNSPECIFIED }, + RepeatedImportMessage = { new ImportMessage { D = 20 }, new ImportMessage { D = 25 } }, + RepeatedInt32 = { 100, 200 }, + RepeatedInt64 = { 3210987654321, long.MaxValue }, + RepeatedNestedEnum = { TestAllTypes.Types.NestedEnum.FOO, TestAllTypes.Types.NestedEnum.NEG }, + RepeatedNestedMessage = { new TestAllTypes.Types.NestedMessage { Bb = 35 }, new TestAllTypes.Types.NestedMessage { Bb = 10 } }, + RepeatedPublicImportMessage = { new PublicImportMessage { E = 54 }, new PublicImportMessage { E = -1 } }, + RepeatedSfixed32 = { -123, 123 }, + RepeatedSfixed64 = { -12345678901234, 12345678901234 }, + RepeatedSint32 = { -456, 100 }, + RepeatedSint64 = { -12345678901235, 123 }, + RepeatedString = { "foo", "bar" }, + RepeatedUint32 = { uint.MaxValue, uint.MinValue }, + RepeatedUint64 = { ulong.MaxValue, uint.MinValue } + }; + + byte[] bytes = message.ToByteArray(); + TestAllTypes parsed = TestAllTypes.Parser.ParseFrom(bytes); + Assert.AreEqual(message, parsed); } } -} \ No newline at end of file +} diff --git a/csharp/src/ProtocolBuffers.Test/IssuesTest.cs b/csharp/src/ProtocolBuffers.Test/IssuesTest.cs index ce7e5f09..87960aab 100644 --- a/csharp/src/ProtocolBuffers.Test/IssuesTest.cs +++ b/csharp/src/ProtocolBuffers.Test/IssuesTest.cs @@ -34,13 +34,12 @@ #endregion - -using Google.ProtocolBuffers.Descriptors; +using Google.Protobuf.Descriptors; using UnitTest.Issues.TestProtos; using NUnit.Framework; -namespace Google.ProtocolBuffers +namespace Google.Protobuf { /// /// Tests for issues which aren't easily compartmentalized into other unit tests. @@ -51,10 +50,11 @@ namespace Google.ProtocolBuffers [Test] public void FieldCalledItem() { - ItemField message = new ItemField.Builder { Item = 3 }.Build(); + ItemField message = new ItemField { Item = 3 }; FieldDescriptor field = ItemField.Descriptor.FindFieldByName("item"); Assert.NotNull(field); - Assert.AreEqual(3, (int)message[field]); + // TODO(jonskeet): Reflection... + // Assert.AreEqual(3, (int)message[field]); } } } diff --git a/csharp/src/ProtocolBuffers.Test/MessageStreamIteratorTest.cs b/csharp/src/ProtocolBuffers.Test/MessageStreamIteratorTest.cs deleted file mode 100644 index 4754ce60..00000000 --- a/csharp/src/ProtocolBuffers.Test/MessageStreamIteratorTest.cs +++ /dev/null @@ -1,90 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Collections.Generic; -using System.IO; -using Google.ProtocolBuffers.TestProtos; -using NUnit.Framework; -using NestedMessage = Google.ProtocolBuffers.TestProtos.TestAllTypes.Types.NestedMessage; - -namespace Google.ProtocolBuffers -{ - public class MessageStreamIteratorTest - { - [Test] - public void ThreeMessagesInMemory() - { - MemoryStream stream = new MemoryStream(MessageStreamWriterTest.ThreeMessageData); - IEnumerable iterator = MessageStreamIterator.FromStreamProvider(() => stream); - List messages = new List(iterator); - - Assert.AreEqual(3, messages.Count); - Assert.AreEqual(5, messages[0].Bb); - Assert.AreEqual(1500, messages[1].Bb); - Assert.IsFalse(messages[2].HasBb); - } - - [Test] - public void ManyMessagesShouldNotTriggerSizeAlert() - { - int messageSize = TestUtil.GetAllSet().SerializedSize; - // Enough messages to trigger the alert unless we've reset the size - // Note that currently we need to make this big enough to copy two whole buffers, - // as otherwise when we refill the buffer the second type, the alert triggers instantly. - int correctCount = (CodedInputStream.BufferSize*2)/messageSize + 1; - using (MemoryStream stream = new MemoryStream()) - { - MessageStreamWriter writer = new MessageStreamWriter(stream); - for (int i = 0; i < correctCount; i++) - { - writer.Write(TestUtil.GetAllSet()); - } - writer.Flush(); - - stream.Position = 0; - - int count = 0; - foreach (var message in MessageStreamIterator.FromStreamProvider(() => stream) - .WithSizeLimit(CodedInputStream.BufferSize*2)) - { - count++; - TestUtil.AssertAllFieldsSet(message); - } - Assert.AreEqual(correctCount, count); - } - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers.Test/MessageStreamWriterTest.cs b/csharp/src/ProtocolBuffers.Test/MessageStreamWriterTest.cs deleted file mode 100644 index 030804ee..00000000 --- a/csharp/src/ProtocolBuffers.Test/MessageStreamWriterTest.cs +++ /dev/null @@ -1,78 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.IO; -using NUnit.Framework; -using NestedMessage = Google.ProtocolBuffers.TestProtos.TestAllTypes.Types.NestedMessage; - -namespace Google.ProtocolBuffers -{ - public class MessageStreamWriterTest - { - internal static readonly byte[] ThreeMessageData = new byte[] - { - (1 << 3) | 2, 2, - // Field 1, 2 bytes long (first message) - (1 << 3) | 0, 5, // Field 1, value 5 - (1 << 3) | 2, 3, - // Field 1, 3 bytes long (second message) - (1 << 3) | 0, (1500 & 0x7f) | 0x80, 1500 >> 7, - // Field 1, value 1500 - (1 << 3) | 2, 0, // Field 1, no data (third message) - }; - - [Test] - public void ThreeMessages() - { - NestedMessage message1 = new NestedMessage.Builder {Bb = 5}.Build(); - NestedMessage message2 = new NestedMessage.Builder {Bb = 1500}.Build(); - NestedMessage message3 = new NestedMessage.Builder().Build(); - - byte[] data; - using (MemoryStream stream = new MemoryStream()) - { - MessageStreamWriter writer = new MessageStreamWriter(stream); - writer.Write(message1); - writer.Write(message2); - writer.Write(message3); - writer.Flush(); - data = stream.ToArray(); - } - - TestUtil.AssertEqualBytes(ThreeMessageData, data); - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers.Test/MessageTest.cs b/csharp/src/ProtocolBuffers.Test/MessageTest.cs deleted file mode 100644 index e746c01a..00000000 --- a/csharp/src/ProtocolBuffers.Test/MessageTest.cs +++ /dev/null @@ -1,344 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.IO; -using Google.ProtocolBuffers.Descriptors; -using Google.ProtocolBuffers.TestProtos; -using NUnit.Framework; - -namespace Google.ProtocolBuffers -{ - /// - /// Miscellaneous tests for message operations that apply to both - /// generated and dynamic messages. - /// - public class MessageTest - { - // ================================================================= - // Message-merging tests. - - private static readonly TestAllTypes MergeSource = new TestAllTypes.Builder - { - OptionalInt32 = 1, - OptionalString = "foo", - OptionalForeignMessage = - ForeignMessage.DefaultInstance, - }.AddRepeatedString("bar").Build(); - - private static readonly TestAllTypes MergeDest = new TestAllTypes.Builder - { - OptionalInt64 = 2, - OptionalString = "baz", - OptionalForeignMessage = - new ForeignMessage.Builder {C = 3}.Build(), - }.AddRepeatedString("qux").Build(); - - private const string MergeResultText = - "optional_int32: 1\n" + - "optional_int64: 2\n" + - "optional_string: \"foo\"\n" + - "optional_foreign_message {\n" + - " c: 3\n" + - "}\n" + - "repeated_string: \"qux\"\n" + - "repeated_string: \"bar\"\n"; - - [Test] - public void MergeFrom() - { - TestAllTypes result = TestAllTypes.CreateBuilder(MergeDest).MergeFrom(MergeSource).Build(); - - Assert.AreEqual(MergeResultText, result.ToString()); - } - - /// - /// Test merging a DynamicMessage into a GeneratedMessage. - /// As long as they have the same descriptor, this should work, but it is an - /// entirely different code path. - /// - [Test] - public void MergeFromDynamic() - { - TestAllTypes result = (TestAllTypes) TestAllTypes.CreateBuilder(MergeDest) - .MergeFrom(DynamicMessage.CreateBuilder(MergeSource).Build()) - .Build(); - - Assert.AreEqual(MergeResultText, result.ToString()); - } - - /// - /// Test merging two DynamicMessages. - /// - [Test] - public void DynamicMergeFrom() - { - DynamicMessage result = (DynamicMessage) DynamicMessage.CreateBuilder(MergeDest) - .MergeFrom( - (DynamicMessage) - DynamicMessage.CreateBuilder(MergeSource).Build()) - .Build(); - - Assert.AreEqual(MergeResultText, result.ToString()); - } - - // ================================================================= - // Required-field-related tests. - - private static readonly TestRequired TestRequiredUninitialized = TestRequired.DefaultInstance; - - private static readonly TestRequired TestRequiredInitialized = new TestRequired.Builder - { - A = 1, - B = 2, - C = 3 - }.Build(); - - [Test] - public void Initialization() - { - TestRequired.Builder builder = TestRequired.CreateBuilder(); - - Assert.IsFalse(builder.IsInitialized); - builder.A = 1; - Assert.IsFalse(builder.IsInitialized); - builder.B = 1; - Assert.IsFalse(builder.IsInitialized); - builder.C = 1; - Assert.IsTrue(builder.IsInitialized); - } - - [Test] - public void UninitializedBuilderToString() - { - TestRequired.Builder builder = TestRequired.CreateBuilder().SetA(1); - Assert.AreEqual("a: 1\n", builder.ToString()); - } - - [Test] - public void RequiredForeign() - { - TestRequiredForeign.Builder builder = TestRequiredForeign.CreateBuilder(); - - Assert.IsTrue(builder.IsInitialized); - - builder.SetOptionalMessage(TestRequiredUninitialized); - Assert.IsFalse(builder.IsInitialized); - - builder.SetOptionalMessage(TestRequiredInitialized); - Assert.IsTrue(builder.IsInitialized); - - builder.AddRepeatedMessage(TestRequiredUninitialized); - Assert.IsFalse(builder.IsInitialized); - - builder.SetRepeatedMessage(0, TestRequiredInitialized); - Assert.IsTrue(builder.IsInitialized); - } - - [Test] - public void RequiredExtension() - { - TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder(); - - Assert.IsTrue(builder.IsInitialized); - - builder.SetExtension(TestRequired.Single, TestRequiredUninitialized); - Assert.IsFalse(builder.IsInitialized); - - builder.SetExtension(TestRequired.Single, TestRequiredInitialized); - Assert.IsTrue(builder.IsInitialized); - - builder.AddExtension(TestRequired.Multi, TestRequiredUninitialized); - Assert.IsFalse(builder.IsInitialized); - - builder.SetExtension(TestRequired.Multi, 0, TestRequiredInitialized); - Assert.IsTrue(builder.IsInitialized); - } - - [Test] - public void RequiredDynamic() - { - MessageDescriptor descriptor = TestRequired.Descriptor; - DynamicMessage.Builder builder = DynamicMessage.CreateBuilder(descriptor); - - Assert.IsFalse(builder.IsInitialized); - builder[descriptor.FindDescriptor("a")] = 1; - Assert.IsFalse(builder.IsInitialized); - builder[descriptor.FindDescriptor("b")] = 1; - Assert.IsFalse(builder.IsInitialized); - builder[descriptor.FindDescriptor("c")] = 1; - Assert.IsTrue(builder.IsInitialized); - } - - [Test] - public void RequiredDynamicForeign() - { - MessageDescriptor descriptor = TestRequiredForeign.Descriptor; - DynamicMessage.Builder builder = DynamicMessage.CreateBuilder(descriptor); - - Assert.IsTrue(builder.IsInitialized); - - builder[descriptor.FindDescriptor("optional_message")] = TestRequiredUninitialized; - Assert.IsFalse(builder.IsInitialized); - - builder[descriptor.FindDescriptor("optional_message")] = TestRequiredInitialized; - Assert.IsTrue(builder.IsInitialized); - - builder.AddRepeatedField(descriptor.FindDescriptor("repeated_message"), - TestRequiredUninitialized); - Assert.IsFalse(builder.IsInitialized); - - builder.SetRepeatedField(descriptor.FindDescriptor("repeated_message"), 0, - TestRequiredInitialized); - Assert.IsTrue(builder.IsInitialized); - } - - [Test] - public void UninitializedException() - { - var e = Assert.Throws(() => TestRequired.CreateBuilder().Build()); - Assert.AreEqual("Message missing required fields: a, b, c", e.Message); - } - - [Test] - public void BuildPartial() - { - // We're mostly testing that no exception is thrown. - TestRequired message = TestRequired.CreateBuilder().BuildPartial(); - Assert.IsFalse(message.IsInitialized); - } - - [Test] - public void NestedUninitializedException() - { - var e = Assert.Throws(() => TestRequiredForeign.CreateBuilder() - .SetOptionalMessage(TestRequiredUninitialized) - .AddRepeatedMessage(TestRequiredUninitialized) - .AddRepeatedMessage(TestRequiredUninitialized) - .Build()); - Assert.AreEqual( - "Message missing required fields: " + - "optional_message.a, " + - "optional_message.b, " + - "optional_message.c, " + - "repeated_message[0].a, " + - "repeated_message[0].b, " + - "repeated_message[0].c, " + - "repeated_message[1].a, " + - "repeated_message[1].b, " + - "repeated_message[1].c", - e.Message); - } - - [Test] - public void BuildNestedPartial() - { - // We're mostly testing that no exception is thrown. - TestRequiredForeign message = - TestRequiredForeign.CreateBuilder() - .SetOptionalMessage(TestRequiredUninitialized) - .AddRepeatedMessage(TestRequiredUninitialized) - .AddRepeatedMessage(TestRequiredUninitialized) - .BuildPartial(); - Assert.IsFalse(message.IsInitialized); - } - - [Test] - public void ParseUninitialized() - { - var e = Assert.Throws(() => TestRequired.ParseFrom(ByteString.Empty)); - Assert.AreEqual("Message missing required fields: a, b, c", e.Message); - } - - [Test] - public void ParseNestedUnititialized() - { - ByteString data = - TestRequiredForeign.CreateBuilder() - .SetOptionalMessage(TestRequiredUninitialized) - .AddRepeatedMessage(TestRequiredUninitialized) - .AddRepeatedMessage(TestRequiredUninitialized) - .BuildPartial().ToByteString(); - - var e = Assert.Throws(() => TestRequiredForeign.ParseFrom(data)); - Assert.AreEqual( - "Message missing required fields: " + - "optional_message.a, " + - "optional_message.b, " + - "optional_message.c, " + - "repeated_message[0].a, " + - "repeated_message[0].b, " + - "repeated_message[0].c, " + - "repeated_message[1].a, " + - "repeated_message[1].b, " + - "repeated_message[1].c", - e.Message); - } - - [Test] - public void DynamicUninitializedException() - { - var e = Assert.Throws(() => DynamicMessage.CreateBuilder(TestRequired.Descriptor).Build()); - Assert.AreEqual("Message missing required fields: a, b, c", e.Message); - } - - [Test] - public void DynamicBuildPartial() - { - // We're mostly testing that no exception is thrown. - DynamicMessage message = DynamicMessage.CreateBuilder(TestRequired.Descriptor).BuildPartial(); - Assert.IsFalse(message.Initialized); - } - - [Test] - public void DynamicParseUnititialized() - { - MessageDescriptor descriptor = TestRequired.Descriptor; - var e = Assert.Throws(() => DynamicMessage.ParseFrom(descriptor, ByteString.Empty)); - Assert.AreEqual("Message missing required fields: a, b, c", e.Message); - } - - [Test] - public void PackedTypesWrittenDirectlyToStream() - { - TestPackedTypes message = new TestPackedTypes.Builder {PackedInt32List = {0, 1, 2}}.Build(); - MemoryStream stream = new MemoryStream(); - message.WriteTo(stream); - stream.Position = 0; - TestPackedTypes readMessage = TestPackedTypes.ParseFrom(stream); - Assert.AreEqual(message, readMessage); - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers.Test/MessageUtilTest.cs b/csharp/src/ProtocolBuffers.Test/MessageUtilTest.cs deleted file mode 100644 index 72909660..00000000 --- a/csharp/src/ProtocolBuffers.Test/MessageUtilTest.cs +++ /dev/null @@ -1,82 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using Google.ProtocolBuffers.TestProtos; -using NUnit.Framework; - -namespace Google.ProtocolBuffers -{ - public class MessageUtilTest - { - [Test] - public void NullTypeName() - { - Assert.Throws(() => MessageUtil.GetDefaultMessage((string) null)); - } - - [Test] - public void InvalidTypeName() - { - Assert.Throws(() => MessageUtil.GetDefaultMessage("invalidtypename")); - } - - [Test] - public void ValidTypeName() - { - Assert.AreSame(TestAllTypes.DefaultInstance, - MessageUtil.GetDefaultMessage(typeof(TestAllTypes).AssemblyQualifiedName)); - } - - [Test] - public void NullType() - { - Assert.Throws(() => MessageUtil.GetDefaultMessage((Type)null)); - } - - [Test] - public void NonMessageType() - { - Assert.Throws(() => MessageUtil.GetDefaultMessage(typeof(string))); - } - - [Test] - public void ValidType() - { - Assert.AreSame(TestAllTypes.DefaultInstance, MessageUtil.GetDefaultMessage(typeof(TestAllTypes))); - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers.Test/NameHelpersTest.cs b/csharp/src/ProtocolBuffers.Test/NameHelpersTest.cs deleted file mode 100644 index edd3ccd9..00000000 --- a/csharp/src/ProtocolBuffers.Test/NameHelpersTest.cs +++ /dev/null @@ -1,81 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using NUnit.Framework; - -namespace Google.ProtocolBuffers -{ - public class NameHelpersTest - { - [Test] - public void UnderscoresToPascalCase() - { - Assert.AreEqual("FooBar", NameHelpers.UnderscoresToPascalCase("Foo_bar")); - Assert.AreEqual("FooBar", NameHelpers.UnderscoresToPascalCase("foo_bar")); - Assert.AreEqual("Foo0Bar", NameHelpers.UnderscoresToPascalCase("Foo0bar")); - Assert.AreEqual("FooBar", NameHelpers.UnderscoresToPascalCase("Foo_+_Bar")); - - Assert.AreEqual("Bar", NameHelpers.UnderscoresToPascalCase("__+bar")); - Assert.AreEqual("Bar", NameHelpers.UnderscoresToPascalCase("bar_")); - Assert.AreEqual("_0Bar", NameHelpers.UnderscoresToPascalCase("_0bar")); - Assert.AreEqual("_1Bar", NameHelpers.UnderscoresToPascalCase("_1_bar")); - } - - [Test] - public void UnderscoresToCamelCase() - { - Assert.AreEqual("fooBar", NameHelpers.UnderscoresToCamelCase("Foo_bar")); - Assert.AreEqual("fooBar", NameHelpers.UnderscoresToCamelCase("foo_bar")); - Assert.AreEqual("foo0Bar", NameHelpers.UnderscoresToCamelCase("Foo0bar")); - Assert.AreEqual("fooBar", NameHelpers.UnderscoresToCamelCase("Foo_+_Bar")); - - Assert.AreEqual("bar", NameHelpers.UnderscoresToCamelCase("__+bar")); - Assert.AreEqual("bar", NameHelpers.UnderscoresToCamelCase("bar_")); - Assert.AreEqual("_0Bar", NameHelpers.UnderscoresToCamelCase("_0bar")); - Assert.AreEqual("_1Bar", NameHelpers.UnderscoresToCamelCase("_1_bar")); - } - - [Test] - public void StripSuffix() - { - string text = "FooBar"; - Assert.IsFalse(NameHelpers.StripSuffix(ref text, "Foo")); - Assert.AreEqual("FooBar", text); - Assert.IsTrue(NameHelpers.StripSuffix(ref text, "Bar")); - Assert.AreEqual("Foo", text); - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers.Test/ProtocolBuffers.Test.csproj b/csharp/src/ProtocolBuffers.Test/ProtocolBuffers.Test.csproj index b4c562d1..31095a5b 100644 --- a/csharp/src/ProtocolBuffers.Test/ProtocolBuffers.Test.csproj +++ b/csharp/src/ProtocolBuffers.Test/ProtocolBuffers.Test.csproj @@ -8,8 +8,8 @@ {DD01ED24-3750-4567-9A23-1DB676A15610} Library Properties - Google.ProtocolBuffers - Google.ProtocolBuffers.Test + Google.Protobuf + Google.Protobuf.Test v4.5 512 true @@ -71,79 +71,37 @@ - - - - - - - - - - - - - - - - - - - + + + + - - - - - - + - - - - - - - - - - - - - - - - - - - {231391AF-449C-4a39-986C-AD7F270F4750} - ProtocolBuffers.Serialization - {6908BDCE-D925-43F3-94AC-A531E6DF2591} ProtocolBuffers - - - - + + + - + \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers/SortedList.cs b/csharp/src/ProtocolBuffers/SortedList.cs deleted file mode 100644 index 2dd7da92..00000000 --- a/csharp/src/ProtocolBuffers/SortedList.cs +++ /dev/null @@ -1,167 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -#if NOSORTEDLIST -using System.Collections; -using System.Collections.Generic; - -namespace Google.ProtocolBuffers -{ - /// - /// Dictionary implementation which always yields keys in sorted order. - /// This is not particularly efficient: it wraps a normal dictionary - /// for most operations, but sorts by key when either iterating or - /// fetching the Keys/Values properties. - /// - internal sealed class SortedList : IDictionary - { - private readonly IDictionary wrapped = new Dictionary(); - - public SortedList() - { - } - - public SortedList(IDictionary dictionary) - { - foreach (KeyValuePair entry in dictionary) - { - Add(entry.Key, entry.Value); - } - } - - public void Add(TKey key, TValue value) - { - wrapped.Add(key, value); - } - - public bool ContainsKey(TKey key) - { - return wrapped.ContainsKey(key); - } - - public ICollection Keys - { - get - { - List keys = new List(wrapped.Count); - foreach (var pair in this) - { - keys.Add(pair.Key); - } - return keys; - } - } - - public bool Remove(TKey key) - { - return wrapped.Remove(key); - } - - public bool TryGetValue(TKey key, out TValue value) - { - return wrapped.TryGetValue(key, out value); - } - - public ICollection Values - { - get - { - List values = new List(wrapped.Count); - foreach (var pair in this) - { - values.Add(pair.Value); - } - return values; - } - } - - public TValue this[TKey key] - { - get { return wrapped[key]; } - set { wrapped[key] = value; } - } - - public void Add(KeyValuePair item) - { - wrapped.Add(item); - } - - public void Clear() - { - wrapped.Clear(); - } - - public bool Contains(KeyValuePair item) - { - return wrapped.Contains(item); - } - - public void CopyTo(KeyValuePair[] array, int arrayIndex) - { - wrapped.CopyTo(array, arrayIndex); - } - - public int Count - { - get { return wrapped.Count; } - } - - public bool IsReadOnly - { - get { return wrapped.IsReadOnly; } - } - - public bool Remove(KeyValuePair item) - { - return wrapped.Remove(item); - } - - public IEnumerator> GetEnumerator() - { - IComparer comparer = Comparer.Default; - var list = new List>(wrapped); - list.Sort((x, y) => comparer.Compare(x.Key, y.Key)); - return list.GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - } -} - -#endif \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers/TextFormat.cs b/csharp/src/ProtocolBuffers/TextFormat.cs deleted file mode 100644 index 6a9180f3..00000000 --- a/csharp/src/ProtocolBuffers/TextFormat.cs +++ /dev/null @@ -1,893 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Text; -using Google.ProtocolBuffers.Descriptors; - -namespace Google.ProtocolBuffers -{ - /// - /// Provides ASCII text formatting support for messages. - /// TODO(jonskeet): Support for alternative line endings. - /// (Easy to print, via TextGenerator. Not sure about parsing.) - /// - public static class TextFormat - { - /// - /// Outputs a textual representation of the Protocol Message supplied into - /// the parameter output. - /// - public static void Print(IMessage message, TextWriter output) - { - TextGenerator generator = new TextGenerator(output, "\n"); - Print(message, generator); - } - - /// - /// Outputs a textual representation of the Protocol Message builder supplied into - /// the parameter output. - /// - public static void Print(IBuilder builder, TextWriter output) - { - TextGenerator generator = new TextGenerator(output, "\n"); - Print(builder, generator); - } - - /// - /// Outputs a textual representation of to . - /// - public static void Print(UnknownFieldSet fields, TextWriter output) - { - TextGenerator generator = new TextGenerator(output, "\n"); - PrintUnknownFields(fields, generator); - } - - public static string PrintToString(IMessage message) - { - StringWriter text = new StringWriter(); - Print(message, text); - return text.ToString(); - } - - public static string PrintToString(IBuilder builder) - { - StringWriter text = new StringWriter(); - Print(builder, text); - return text.ToString(); - } - - public static string PrintToString(UnknownFieldSet fields) - { - StringWriter text = new StringWriter(); - Print(fields, text); - return text.ToString(); - } - - private static void Print(IMessage message, TextGenerator generator) - { - foreach (KeyValuePair entry in message.AllFields) - { - PrintField(entry.Key, entry.Value, generator); - } - PrintUnknownFields(message.UnknownFields, generator); - } - - private static void Print(IBuilder message, TextGenerator generator) - { - foreach (KeyValuePair entry in message.AllFields) - { - PrintField(entry.Key, entry.Value, generator); - } - PrintUnknownFields(message.UnknownFields, generator); - } - - internal static void PrintField(FieldDescriptor field, object value, TextGenerator generator) - { - if (field.IsRepeated) - { - // Repeated field. Print each element. - foreach (object element in (IEnumerable) value) - { - PrintSingleField(field, element, generator); - } - } - else - { - PrintSingleField(field, value, generator); - } - } - - private static void PrintSingleField(FieldDescriptor field, Object value, TextGenerator generator) - { - if (field.IsExtension) - { - generator.Print("["); - // We special-case MessageSet elements for compatibility with proto1. - if (field.ContainingType.Options.MessageSetWireFormat - && field.FieldType == FieldType.Message - && field.IsOptional - // object equality (TODO(jonskeet): Work out what this comment means!) - && field.ExtensionScope == field.MessageType) - { - generator.Print(field.MessageType.FullName); - } - else - { - generator.Print(field.FullName); - } - generator.Print("]"); - } - else - { - if (field.FieldType == FieldType.Group) - { - // Groups must be serialized with their original capitalization. - generator.Print(field.MessageType.Name); - } - else - { - generator.Print(field.Name); - } - } - - if (field.MappedType == MappedType.Message) - { - generator.Print(" {\n"); - generator.Indent(); - } - else - { - generator.Print(": "); - } - - PrintFieldValue(field, value, generator); - - if (field.MappedType == MappedType.Message) - { - generator.Outdent(); - generator.Print("}"); - } - generator.Print("\n"); - } - - private static void PrintFieldValue(FieldDescriptor field, object value, TextGenerator generator) - { - switch (field.FieldType) - { - // The Float and Double types must specify the "r" format to preserve their precision, otherwise, - // the double to/from string will trim the precision to 6 places. As with other numeric formats - // below, always use the invariant culture so it's predictable. - case FieldType.Float: - generator.Print(((float)value).ToString("r", FrameworkPortability.InvariantCulture)); - break; - case FieldType.Double: - generator.Print(((double)value).ToString("r", FrameworkPortability.InvariantCulture)); - break; - - case FieldType.Int32: - case FieldType.Int64: - case FieldType.SInt32: - case FieldType.SInt64: - case FieldType.SFixed32: - case FieldType.SFixed64: - case FieldType.UInt32: - case FieldType.UInt64: - case FieldType.Fixed32: - case FieldType.Fixed64: - // The simple Object.ToString converts using the current culture. - // We want to always use the invariant culture so it's predictable. - generator.Print(((IConvertible)value).ToString(FrameworkPortability.InvariantCulture)); - break; - case FieldType.Bool: - // Explicitly use the Java true/false - generator.Print((bool) value ? "true" : "false"); - break; - - case FieldType.String: - generator.Print("\""); - generator.Print(EscapeText((string) value)); - generator.Print("\""); - break; - - case FieldType.Bytes: - { - generator.Print("\""); - generator.Print(EscapeBytes((ByteString) value)); - generator.Print("\""); - break; - } - - case FieldType.Enum: - { - if (value is IEnumLite && !(value is EnumValueDescriptor)) - { - throw new NotSupportedException("Lite enumerations are not supported."); - } - generator.Print(((EnumValueDescriptor) value).Name); - break; - } - - case FieldType.Message: - case FieldType.Group: - if (value is IMessageLite && !(value is IMessage)) - { - throw new NotSupportedException("Lite messages are not supported."); - } - Print((IMessage) value, generator); - break; - } - } - - private static void PrintUnknownFields(UnknownFieldSet unknownFields, TextGenerator generator) - { - foreach (KeyValuePair entry in unknownFields.FieldDictionary) - { - String prefix = entry.Key.ToString() + ": "; - UnknownField field = entry.Value; - - foreach (ulong value in field.VarintList) - { - generator.Print(prefix); - generator.Print(value.ToString()); - generator.Print("\n"); - } - foreach (uint value in field.Fixed32List) - { - generator.Print(prefix); - generator.Print(string.Format("0x{0:x8}", value)); - generator.Print("\n"); - } - foreach (ulong value in field.Fixed64List) - { - generator.Print(prefix); - generator.Print(string.Format("0x{0:x16}", value)); - generator.Print("\n"); - } - foreach (ByteString value in field.LengthDelimitedList) - { - generator.Print(entry.Key.ToString()); - generator.Print(": \""); - generator.Print(EscapeBytes(value)); - generator.Print("\"\n"); - } - foreach (UnknownFieldSet value in field.GroupList) - { - generator.Print(entry.Key.ToString()); - generator.Print(" {\n"); - generator.Indent(); - PrintUnknownFields(value, generator); - generator.Outdent(); - generator.Print("}\n"); - } - } - } - - public static ulong ParseUInt64(string text) - { - return (ulong) ParseInteger(text, false, true); - } - - public static long ParseInt64(string text) - { - return ParseInteger(text, true, true); - } - - public static uint ParseUInt32(string text) - { - return (uint) ParseInteger(text, false, false); - } - - public static int ParseInt32(string text) - { - return (int) ParseInteger(text, true, false); - } - - public static float ParseFloat(string text) - { - switch (text) - { - case "-inf": - case "-infinity": - case "-inff": - case "-infinityf": - return float.NegativeInfinity; - case "inf": - case "infinity": - case "inff": - case "infinityf": - return float.PositiveInfinity; - case "nan": - case "nanf": - return float.NaN; - default: - return float.Parse(text, FrameworkPortability.InvariantCulture); - } - } - - public static double ParseDouble(string text) - { - switch (text) - { - case "-inf": - case "-infinity": - return double.NegativeInfinity; - case "inf": - case "infinity": - return double.PositiveInfinity; - case "nan": - return double.NaN; - default: - return double.Parse(text, FrameworkPortability.InvariantCulture); - } - } - - /// - /// Parses an integer in hex (leading 0x), decimal (no prefix) or octal (leading 0). - /// Only a negative sign is permitted, and it must come before the radix indicator. - /// - private static long ParseInteger(string text, bool isSigned, bool isLong) - { - string original = text; - bool negative = false; - if (text.StartsWith("-")) - { - if (!isSigned) - { - throw new FormatException("Number must be positive: " + original); - } - negative = true; - text = text.Substring(1); - } - - int radix = 10; - if (text.StartsWith("0x")) - { - radix = 16; - text = text.Substring(2); - } - else if (text.StartsWith("0")) - { - radix = 8; - } - - ulong result; - try - { - // Workaround for https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=278448 - // We should be able to use Convert.ToUInt64 for all cases. - result = radix == 10 ? ulong.Parse(text) : Convert.ToUInt64(text, radix); - } - catch (OverflowException) - { - // Convert OverflowException to FormatException so there's a single exception type this method can throw. - string numberDescription = string.Format("{0}-bit {1}signed integer", isLong ? 64 : 32, - isSigned ? "" : "un"); - throw new FormatException("Number out of range for " + numberDescription + ": " + original); - } - - if (negative) - { - ulong max = isLong ? 0x8000000000000000UL : 0x80000000L; - if (result > max) - { - string numberDescription = string.Format("{0}-bit signed integer", isLong ? 64 : 32); - throw new FormatException("Number out of range for " + numberDescription + ": " + original); - } - return -((long) result); - } - else - { - ulong max = isSigned - ? (isLong ? (ulong) long.MaxValue : int.MaxValue) - : (isLong ? ulong.MaxValue : uint.MaxValue); - if (result > max) - { - string numberDescription = string.Format("{0}-bit {1}signed integer", isLong ? 64 : 32, - isSigned ? "" : "un"); - throw new FormatException("Number out of range for " + numberDescription + ": " + original); - } - return (long) result; - } - } - - /// - /// Tests a character to see if it's an octal digit. - /// - private static bool IsOctal(char c) - { - return '0' <= c && c <= '7'; - } - - /// - /// Tests a character to see if it's a hex digit. - /// - private static bool IsHex(char c) - { - return ('0' <= c && c <= '9') || - ('a' <= c && c <= 'f') || - ('A' <= c && c <= 'F'); - } - - /// - /// Interprets a character as a digit (in any base up to 36) and returns the - /// numeric value. - /// - private static int ParseDigit(char c) - { - if ('0' <= c && c <= '9') - { - return c - '0'; - } - else if ('a' <= c && c <= 'z') - { - return c - 'a' + 10; - } - else - { - return c - 'A' + 10; - } - } - - /// - /// Unescapes a text string as escaped using . - /// Two-digit hex escapes (starting with "\x" are also recognised. - /// - public static string UnescapeText(string input) - { - return UnescapeBytes(input).ToStringUtf8(); - } - - /// - /// Like but escapes a text string. - /// The string is first encoded as UTF-8, then each byte escaped individually. - /// The returned value is guaranteed to be entirely ASCII. - /// - public static string EscapeText(string input) - { - return EscapeBytes(ByteString.CopyFromUtf8(input)); - } - - /// - /// Escapes bytes in the format used in protocol buffer text format, which - /// is the same as the format used for C string literals. All bytes - /// that are not printable 7-bit ASCII characters are escaped, as well as - /// backslash, single-quote, and double-quote characters. Characters for - /// which no defined short-hand escape sequence is defined will be escaped - /// using 3-digit octal sequences. - /// The returned value is guaranteed to be entirely ASCII. - /// - public static String EscapeBytes(ByteString input) - { - StringBuilder builder = new StringBuilder(input.Length); - foreach (byte b in input) - { - switch (b) - { - // C# does not use \a or \v - case 0x07: - builder.Append("\\a"); - break; - case (byte) '\b': - builder.Append("\\b"); - break; - case (byte) '\f': - builder.Append("\\f"); - break; - case (byte) '\n': - builder.Append("\\n"); - break; - case (byte) '\r': - builder.Append("\\r"); - break; - case (byte) '\t': - builder.Append("\\t"); - break; - case 0x0b: - builder.Append("\\v"); - break; - case (byte) '\\': - builder.Append("\\\\"); - break; - case (byte) '\'': - builder.Append("\\\'"); - break; - case (byte) '"': - builder.Append("\\\""); - break; - default: - if (b >= 0x20 && b < 128) - { - builder.Append((char) b); - } - else - { - builder.Append('\\'); - builder.Append((char) ('0' + ((b >> 6) & 3))); - builder.Append((char) ('0' + ((b >> 3) & 7))); - builder.Append((char) ('0' + (b & 7))); - } - break; - } - } - return builder.ToString(); - } - - /// - /// Performs string unescaping from C style (octal, hex, form feeds, tab etc) into a byte string. - /// - public static ByteString UnescapeBytes(string input) - { - byte[] result = new byte[input.Length]; - int pos = 0; - for (int i = 0; i < input.Length; i++) - { - char c = input[i]; - if (c > 127 || c < 32) - { - throw new FormatException("Escaped string must only contain ASCII"); - } - if (c != '\\') - { - result[pos++] = (byte) c; - continue; - } - if (i + 1 >= input.Length) - { - throw new FormatException("Invalid escape sequence: '\\' at end of string."); - } - - i++; - c = input[i]; - if (c >= '0' && c <= '7') - { - // Octal escape. - int code = ParseDigit(c); - if (i + 1 < input.Length && IsOctal(input[i + 1])) - { - i++; - code = code*8 + ParseDigit(input[i]); - } - if (i + 1 < input.Length && IsOctal(input[i + 1])) - { - i++; - code = code*8 + ParseDigit(input[i]); - } - result[pos++] = (byte) code; - } - else - { - switch (c) - { - case 'a': - result[pos++] = 0x07; - break; - case 'b': - result[pos++] = (byte) '\b'; - break; - case 'f': - result[pos++] = (byte) '\f'; - break; - case 'n': - result[pos++] = (byte) '\n'; - break; - case 'r': - result[pos++] = (byte) '\r'; - break; - case 't': - result[pos++] = (byte) '\t'; - break; - case 'v': - result[pos++] = 0x0b; - break; - case '\\': - result[pos++] = (byte) '\\'; - break; - case '\'': - result[pos++] = (byte) '\''; - break; - case '"': - result[pos++] = (byte) '\"'; - break; - - case 'x': - // hex escape - int code; - if (i + 1 < input.Length && IsHex(input[i + 1])) - { - i++; - code = ParseDigit(input[i]); - } - else - { - throw new FormatException("Invalid escape sequence: '\\x' with no digits"); - } - if (i + 1 < input.Length && IsHex(input[i + 1])) - { - ++i; - code = code*16 + ParseDigit(input[i]); - } - result[pos++] = (byte) code; - break; - - default: - throw new FormatException("Invalid escape sequence: '\\" + c + "'"); - } - } - } - - return ByteString.CopyFrom(result, 0, pos); - } - - public static void Merge(string text, IBuilder builder) - { - Merge(text, ExtensionRegistry.Empty, builder); - } - - public static void Merge(TextReader reader, IBuilder builder) - { - Merge(reader, ExtensionRegistry.Empty, builder); - } - - public static void Merge(TextReader reader, ExtensionRegistry registry, IBuilder builder) - { - Merge(reader.ReadToEnd(), registry, builder); - } - - public static void Merge(string text, ExtensionRegistry registry, IBuilder builder) - { - TextTokenizer tokenizer = new TextTokenizer(text); - - while (!tokenizer.AtEnd) - { - MergeField(tokenizer, registry, builder); - } - } - - /// - /// Parses a single field from the specified tokenizer and merges it into - /// the builder. - /// - private static void MergeField(TextTokenizer tokenizer, ExtensionRegistry extensionRegistry, - IBuilder builder) - { - FieldDescriptor field; - MessageDescriptor type = builder.DescriptorForType; - ExtensionInfo extension = null; - - if (tokenizer.TryConsume("[")) - { - // An extension. - StringBuilder name = new StringBuilder(tokenizer.ConsumeIdentifier()); - while (tokenizer.TryConsume(".")) - { - name.Append("."); - name.Append(tokenizer.ConsumeIdentifier()); - } - - extension = extensionRegistry.FindByName(type, name.ToString()); - - if (extension == null) - { - throw tokenizer.CreateFormatExceptionPreviousToken("Extension \"" + name + - "\" not found in the ExtensionRegistry."); - } - else if (extension.Descriptor.ContainingType != type) - { - throw tokenizer.CreateFormatExceptionPreviousToken("Extension \"" + name + - "\" does not extend message type \"" + - type.FullName + "\"."); - } - - tokenizer.Consume("]"); - - field = extension.Descriptor; - } - else - { - String name = tokenizer.ConsumeIdentifier(); - field = type.FindDescriptor(name); - - // Group names are expected to be capitalized as they appear in the - // .proto file, which actually matches their type names, not their field - // names. - if (field == null) - { - // Explicitly specify the invariant culture so that this code does not break when - // executing in Turkey. - String lowerName = name.ToLowerInvariant(); - field = type.FindDescriptor(lowerName); - // If the case-insensitive match worked but the field is NOT a group, - // TODO(jonskeet): What? Java comment ends here! - if (field != null && field.FieldType != FieldType.Group) - { - field = null; - } - } - // Again, special-case group names as described above. - if (field != null && field.FieldType == FieldType.Group && field.MessageType.Name != name) - { - field = null; - } - - if (field == null) - { - throw tokenizer.CreateFormatExceptionPreviousToken( - "Message type \"" + type.FullName + "\" has no field named \"" + name + "\"."); - } - } - - object value = null; - - if (field.MappedType == MappedType.Message) - { - tokenizer.TryConsume(":"); // optional - - String endToken; - if (tokenizer.TryConsume("<")) - { - endToken = ">"; - } - else - { - tokenizer.Consume("{"); - endToken = "}"; - } - - IBuilder subBuilder; - if (extension == null) - { - subBuilder = builder.CreateBuilderForField(field); - } - else - { - subBuilder = extension.DefaultInstance.WeakCreateBuilderForType() as IBuilder; - if (subBuilder == null) - { - throw new NotSupportedException("Lite messages are not supported."); - } - } - - while (!tokenizer.TryConsume(endToken)) - { - if (tokenizer.AtEnd) - { - throw tokenizer.CreateFormatException("Expected \"" + endToken + "\"."); - } - MergeField(tokenizer, extensionRegistry, subBuilder); - } - - value = subBuilder.WeakBuild(); - } - else - { - tokenizer.Consume(":"); - - switch (field.FieldType) - { - case FieldType.Int32: - case FieldType.SInt32: - case FieldType.SFixed32: - value = tokenizer.ConsumeInt32(); - break; - - case FieldType.Int64: - case FieldType.SInt64: - case FieldType.SFixed64: - value = tokenizer.ConsumeInt64(); - break; - - case FieldType.UInt32: - case FieldType.Fixed32: - value = tokenizer.ConsumeUInt32(); - break; - - case FieldType.UInt64: - case FieldType.Fixed64: - value = tokenizer.ConsumeUInt64(); - break; - - case FieldType.Float: - value = tokenizer.ConsumeFloat(); - break; - - case FieldType.Double: - value = tokenizer.ConsumeDouble(); - break; - - case FieldType.Bool: - value = tokenizer.ConsumeBoolean(); - break; - - case FieldType.String: - value = tokenizer.ConsumeString(); - break; - - case FieldType.Bytes: - value = tokenizer.ConsumeByteString(); - break; - - case FieldType.Enum: - { - EnumDescriptor enumType = field.EnumType; - - if (tokenizer.LookingAtInteger()) - { - int number = tokenizer.ConsumeInt32(); - value = enumType.FindValueByNumber(number); - if (value == null) - { - throw tokenizer.CreateFormatExceptionPreviousToken( - "Enum type \"" + enumType.FullName + - "\" has no value with number " + number + "."); - } - } - else - { - String id = tokenizer.ConsumeIdentifier(); - value = enumType.FindValueByName(id); - if (value == null) - { - throw tokenizer.CreateFormatExceptionPreviousToken( - "Enum type \"" + enumType.FullName + - "\" has no value named \"" + id + "\"."); - } - } - - break; - } - - case FieldType.Message: - case FieldType.Group: - throw new InvalidOperationException("Can't get here."); - } - } - - if (field.IsRepeated) - { - builder.WeakAddRepeatedField(field, value); - } - else - { - builder.SetField(field, value); - } - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers/TextGenerator.cs b/csharp/src/ProtocolBuffers/TextGenerator.cs index 30cbf0fd..80910ba1 100644 --- a/csharp/src/ProtocolBuffers/TextGenerator.cs +++ b/csharp/src/ProtocolBuffers/TextGenerator.cs @@ -38,7 +38,7 @@ using System; using System.IO; using System.Text; -namespace Google.ProtocolBuffers +namespace Google.Protobuf { /// /// Helper class to control indentation. Used for TextFormat and by ProtoGen. diff --git a/csharp/src/ProtocolBuffers/TextTokenizer.cs b/csharp/src/ProtocolBuffers/TextTokenizer.cs deleted file mode 100644 index 5bb27fd0..00000000 --- a/csharp/src/ProtocolBuffers/TextTokenizer.cs +++ /dev/null @@ -1,501 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Globalization; -using System.Text.RegularExpressions; - -namespace Google.ProtocolBuffers -{ - /// - /// Represents a stream of tokens parsed from a string. - /// - internal sealed class TextTokenizer - { - private readonly string text; - private string currentToken; - - /// - /// The character index within the text to perform the next regex match at. - /// - private int matchPos = 0; - - /// - /// The character index within the text at which the current token begins. - /// - private int pos = 0; - - /// - /// The line number of the current token. - /// - private int line = 0; - - /// - /// The column number of the current token. - /// - private int column = 0; - - /// - /// The line number of the previous token. - /// - private int previousLine = 0; - - /// - /// The column number of the previous token. - /// - private int previousColumn = 0; - - // Note: atomic groups used to mimic possessive quantifiers in Java in both of these regexes - internal static readonly Regex WhitespaceAndCommentPattern = new Regex("\\G(?>(\\s|(#.*$))+)", - FrameworkPortability. - CompiledRegexWhereAvailable | - RegexOptions.Multiline); - - private static readonly Regex TokenPattern = new Regex( - "\\G[a-zA-Z_](?>[0-9a-zA-Z_+-]*)|" + // an identifier - "\\G[0-9+-](?>[0-9a-zA-Z_.+-]*)|" + // a number - "\\G\"(?>([^\"\\\n\\\\]|\\\\.)*)(\"|\\\\?$)|" + // a double-quoted string - "\\G\'(?>([^\"\\\n\\\\]|\\\\.)*)(\'|\\\\?$)", // a single-quoted string - FrameworkPortability.CompiledRegexWhereAvailable | RegexOptions.Multiline); - - private static readonly Regex DoubleInfinity = new Regex("^-?inf(inity)?$", - FrameworkPortability.CompiledRegexWhereAvailable | - RegexOptions.IgnoreCase); - - private static readonly Regex FloatInfinity = new Regex("^-?inf(inity)?f?$", - FrameworkPortability.CompiledRegexWhereAvailable | - RegexOptions.IgnoreCase); - - private static readonly Regex FloatNan = new Regex("^nanf?$", - FrameworkPortability.CompiledRegexWhereAvailable | - RegexOptions.IgnoreCase); - - /** Construct a tokenizer that parses tokens from the given text. */ - - public TextTokenizer(string text) - { - this.text = text; - SkipWhitespace(); - NextToken(); - } - - /// - /// Are we at the end of the input? - /// - public bool AtEnd - { - get { return currentToken.Length == 0; } - } - - /// - /// Advances to the next token. - /// - public void NextToken() - { - previousLine = line; - previousColumn = column; - - // Advance the line counter to the current position. - while (pos < matchPos) - { - if (text[pos] == '\n') - { - ++line; - column = 0; - } - else - { - ++column; - } - ++pos; - } - - // Match the next token. - if (matchPos == text.Length) - { - // EOF - currentToken = ""; - } - else - { - Match match = TokenPattern.Match(text, matchPos); - if (match.Success) - { - currentToken = match.Value; - matchPos += match.Length; - } - else - { - // Take one character. - currentToken = text[matchPos].ToString(); - matchPos++; - } - - SkipWhitespace(); - } - } - - /// - /// Skip over any whitespace so that matchPos starts at the next token. - /// - private void SkipWhitespace() - { - Match match = WhitespaceAndCommentPattern.Match(text, matchPos); - if (match.Success) - { - matchPos += match.Length; - } - } - - /// - /// If the next token exactly matches the given token, consume it and return - /// true. Otherwise, return false without doing anything. - /// - public bool TryConsume(string token) - { - if (currentToken == token) - { - NextToken(); - return true; - } - return false; - } - - /* - * If the next token exactly matches {@code token}, consume it. Otherwise, - * throw a {@link ParseException}. - */ - - /// - /// If the next token exactly matches the specified one, consume it. - /// Otherwise, throw a FormatException. - /// - /// - public void Consume(string token) - { - if (!TryConsume(token)) - { - throw CreateFormatException("Expected \"" + token + "\"."); - } - } - - /// - /// Returns true if the next token is an integer, but does not consume it. - /// - public bool LookingAtInteger() - { - if (currentToken.Length == 0) - { - return false; - } - - char c = currentToken[0]; - return ('0' <= c && c <= '9') || c == '-' || c == '+'; - } - - /// - /// If the next token is an identifier, consume it and return its value. - /// Otherwise, throw a FormatException. - /// - public string ConsumeIdentifier() - { - foreach (char c in currentToken) - { - if (('a' <= c && c <= 'z') || - ('A' <= c && c <= 'Z') || - ('0' <= c && c <= '9') || - (c == '_') || (c == '.')) - { - // OK - } - else - { - throw CreateFormatException("Expected identifier."); - } - } - - string result = currentToken; - NextToken(); - return result; - } - - /// - /// If the next token is a 32-bit signed integer, consume it and return its - /// value. Otherwise, throw a FormatException. - /// - public int ConsumeInt32() - { - try - { - int result = TextFormat.ParseInt32(currentToken); - NextToken(); - return result; - } - catch (FormatException e) - { - throw CreateIntegerParseException(e); - } - } - - /// - /// If the next token is a 32-bit unsigned integer, consume it and return its - /// value. Otherwise, throw a FormatException. - /// - public uint ConsumeUInt32() - { - try - { - uint result = TextFormat.ParseUInt32(currentToken); - NextToken(); - return result; - } - catch (FormatException e) - { - throw CreateIntegerParseException(e); - } - } - - /// - /// If the next token is a 64-bit signed integer, consume it and return its - /// value. Otherwise, throw a FormatException. - /// - public long ConsumeInt64() - { - try - { - long result = TextFormat.ParseInt64(currentToken); - NextToken(); - return result; - } - catch (FormatException e) - { - throw CreateIntegerParseException(e); - } - } - - /// - /// If the next token is a 64-bit unsigned integer, consume it and return its - /// value. Otherwise, throw a FormatException. - /// - public ulong ConsumeUInt64() - { - try - { - ulong result = TextFormat.ParseUInt64(currentToken); - NextToken(); - return result; - } - catch (FormatException e) - { - throw CreateIntegerParseException(e); - } - } - - /// - /// If the next token is a double, consume it and return its value. - /// Otherwise, throw a FormatException. - /// - public double ConsumeDouble() - { - // We need to parse infinity and nan separately because - // double.Parse() does not accept "inf", "infinity", or "nan". - if (DoubleInfinity.IsMatch(currentToken)) - { - bool negative = currentToken.StartsWith("-"); - NextToken(); - return negative ? double.NegativeInfinity : double.PositiveInfinity; - } - if (currentToken.Equals("nan", StringComparison.OrdinalIgnoreCase)) - { - NextToken(); - return Double.NaN; - } - - try - { - double result = double.Parse(currentToken, FrameworkPortability.InvariantCulture); - NextToken(); - return result; - } - catch (FormatException e) - { - throw CreateFloatParseException(e); - } - catch (OverflowException e) - { - throw CreateFloatParseException(e); - } - } - - /// - /// If the next token is a float, consume it and return its value. - /// Otherwise, throw a FormatException. - /// - public float ConsumeFloat() - { - // We need to parse infinity and nan separately because - // Float.parseFloat() does not accept "inf", "infinity", or "nan". - if (FloatInfinity.IsMatch(currentToken)) - { - bool negative = currentToken.StartsWith("-"); - NextToken(); - return negative ? float.NegativeInfinity : float.PositiveInfinity; - } - if (FloatNan.IsMatch(currentToken)) - { - NextToken(); - return float.NaN; - } - - if (currentToken.EndsWith("f")) - { - currentToken = currentToken.TrimEnd('f'); - } - - try - { - float result = float.Parse(currentToken, FrameworkPortability.InvariantCulture); - NextToken(); - return result; - } - catch (FormatException e) - { - throw CreateFloatParseException(e); - } - catch (OverflowException e) - { - throw CreateFloatParseException(e); - } - } - - /// - /// If the next token is a Boolean, consume it and return its value. - /// Otherwise, throw a FormatException. - /// - public bool ConsumeBoolean() - { - if (currentToken == "true") - { - NextToken(); - return true; - } - if (currentToken == "false") - { - NextToken(); - return false; - } - throw CreateFormatException("Expected \"true\" or \"false\"."); - } - - /// - /// If the next token is a string, consume it and return its (unescaped) value. - /// Otherwise, throw a FormatException. - /// - public string ConsumeString() - { - return ConsumeByteString().ToStringUtf8(); - } - - /// - /// If the next token is a string, consume it, unescape it as a - /// ByteString and return it. Otherwise, throw a FormatException. - /// - public ByteString ConsumeByteString() - { - char quote = currentToken.Length > 0 ? currentToken[0] : '\0'; - if (quote != '\"' && quote != '\'') - { - throw CreateFormatException("Expected string."); - } - - if (currentToken.Length < 2 || - currentToken[currentToken.Length - 1] != quote) - { - throw CreateFormatException("String missing ending quote."); - } - - try - { - string escaped = currentToken.Substring(1, currentToken.Length - 2); - ByteString result = TextFormat.UnescapeBytes(escaped); - NextToken(); - return result; - } - catch (FormatException e) - { - throw CreateFormatException(e.Message); - } - } - - /// - /// Returns a format exception with the current line and column numbers - /// in the description, suitable for throwing. - /// - public FormatException CreateFormatException(string description) - { - // Note: People generally prefer one-based line and column numbers. - return new FormatException((line + 1) + ":" + (column + 1) + ": " + description); - } - - /// - /// Returns a format exception with the line and column numbers of the - /// previous token in the description, suitable for throwing. - /// - public FormatException CreateFormatExceptionPreviousToken(string description) - { - // Note: People generally prefer one-based line and column numbers. - return new FormatException((previousLine + 1) + ":" + (previousColumn + 1) + ": " + description); - } - - /// - /// Constructs an appropriate FormatException for the given existing exception - /// when trying to parse an integer. - /// - private FormatException CreateIntegerParseException(FormatException e) - { - return CreateFormatException("Couldn't parse integer: " + e.Message); - } - - /// - /// Constructs an appropriate FormatException for the given existing exception - /// when trying to parse a float or double. - /// - private FormatException CreateFloatParseException(Exception e) - { - return CreateFormatException("Couldn't parse number: " + e.Message); - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers/ThrowHelper.cs b/csharp/src/ProtocolBuffers/ThrowHelper.cs index 69e5f569..097b5032 100644 --- a/csharp/src/ProtocolBuffers/ThrowHelper.cs +++ b/csharp/src/ProtocolBuffers/ThrowHelper.cs @@ -37,7 +37,7 @@ using System; using System.Collections.Generic; -namespace Google.ProtocolBuffers +namespace Google.Protobuf { /// /// Helper methods for throwing exceptions diff --git a/csharp/src/ProtocolBuffers/UninitializedMessageException.cs b/csharp/src/ProtocolBuffers/UninitializedMessageException.cs deleted file mode 100644 index 9e4f856e..00000000 --- a/csharp/src/ProtocolBuffers/UninitializedMessageException.cs +++ /dev/null @@ -1,208 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Text; - -#if !LITE -using Google.ProtocolBuffers.Collections; -using Google.ProtocolBuffers.Descriptors; - -#endif - -namespace Google.ProtocolBuffers -{ - /// - /// TODO(jonskeet): Write summary text. - /// - public sealed class UninitializedMessageException : Exception - { - private readonly IList missingFields; - - private UninitializedMessageException(IList missingFields) - : base(BuildDescription(missingFields)) - { - this.missingFields = new List(missingFields); - } - - /// - /// Returns a read-only list of human-readable names of - /// required fields missing from this message. Each name - /// is a full path to a field, e.g. "foo.bar[5].baz" - /// - public IList MissingFields - { - get { return missingFields; } - } - - /// - /// Converts this exception into an InvalidProtocolBufferException. - /// When a parsed message is missing required fields, this should be thrown - /// instead of UninitializedMessageException. - /// - public InvalidProtocolBufferException AsInvalidProtocolBufferException() - { - return new InvalidProtocolBufferException(Message); - } - - /// - /// Constructs the description string for a given list of missing fields. - /// - private static string BuildDescription(IEnumerable missingFields) - { - StringBuilder description = new StringBuilder("Message missing required fields: "); - bool first = true; - foreach (string field in missingFields) - { - if (first) - { - first = false; - } - else - { - description.Append(", "); - } - description.Append(field); - } - return description.ToString(); - } - - /// - /// For Lite exceptions that do not known how to enumerate missing fields - /// - public UninitializedMessageException(IMessageLite message) - : base(String.Format("Message {0} is missing required fields", message.GetType())) - { - missingFields = new List(); - } - -#if !LITE - public UninitializedMessageException(IMessage message) - : this(FindMissingFields(message)) - { - } - - /// - /// Returns a list of the full "paths" of missing required - /// fields in the specified message. - /// - private static IList FindMissingFields(IMessage message) - { - List results = new List(); - FindMissingFields(message, "", results); - return results; - } - - /// - /// Recursive helper implementing FindMissingFields. - /// - private static void FindMissingFields(IMessage message, String prefix, List results) - { - foreach (FieldDescriptor field in message.DescriptorForType.Fields) - { - if (field.IsRequired && !message.HasField(field)) - { - results.Add(prefix + field.Name); - } - } - - foreach (KeyValuePair entry in message.AllFields) - { - FieldDescriptor field = entry.Key; - object value = entry.Value; - - if (field.MappedType == MappedType.Message) - { - if (field.IsRepeated) - { - int i = 0; - foreach (object element in (IEnumerable) value) - { - if (element is IMessage) - { - FindMissingFields((IMessage) element, SubMessagePrefix(prefix, field, i++), results); - } - else - { - results.Add(prefix + field.Name); - } - } - } - else - { - if (message.HasField(field)) - { - if (value is IMessage) - { - FindMissingFields((IMessage) value, SubMessagePrefix(prefix, field, -1), results); - } - else - { - results.Add(prefix + field.Name); - } - } - } - } - } - } - - private static String SubMessagePrefix(String prefix, FieldDescriptor field, int index) - { - StringBuilder result = new StringBuilder(prefix); - if (field.IsExtension) - { - result.Append('(') - .Append(field.FullName) - .Append(')'); - } - else - { - result.Append(field.Name); - } - if (index != -1) - { - result.Append('[') - .Append(index) - .Append(']'); - } - result.Append('.'); - return result.ToString(); - } -#endif - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers/UnknownField.cs b/csharp/src/ProtocolBuffers/UnknownField.cs deleted file mode 100644 index 7650b9df..00000000 --- a/csharp/src/ProtocolBuffers/UnknownField.cs +++ /dev/null @@ -1,415 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using Google.ProtocolBuffers.Collections; - -namespace Google.ProtocolBuffers -{ - /// - /// Represents a single field in an UnknownFieldSet. - /// - /// An UnknownField consists of five lists of values. The lists correspond - /// to the five "wire types" used in the protocol buffer binary format. - /// The wire type of each field can be determined from the encoded form alone, - /// without knowing the field's declared type. So, we are able to parse - /// unknown values at least this far and separate them. Normally, only one - /// of the five lists will contain any values, since it is impossible to - /// define a valid message type that declares two different types for the - /// same field number. However, the code is designed to allow for the case - /// where the same unknown field number is encountered using multiple different - /// wire types. - /// - /// UnknownField is an immutable class. To construct one, you must use an - /// UnknownField.Builder. - /// - public sealed class UnknownField - { - public const string UnknownFieldName = "unknown_field"; - private static readonly UnknownField defaultInstance = CreateBuilder().Build(); - private readonly ReadOnlyCollection varintList; - private readonly ReadOnlyCollection fixed32List; - private readonly ReadOnlyCollection fixed64List; - private readonly ReadOnlyCollection lengthDelimitedList; - private readonly ReadOnlyCollection groupList; - - private UnknownField(ReadOnlyCollection varintList, - ReadOnlyCollection fixed32List, - ReadOnlyCollection fixed64List, - ReadOnlyCollection lengthDelimitedList, - ReadOnlyCollection groupList) - { - this.varintList = varintList; - this.fixed32List = fixed32List; - this.fixed64List = fixed64List; - this.lengthDelimitedList = lengthDelimitedList; - this.groupList = groupList; - } - - public static UnknownField DefaultInstance - { - get { return defaultInstance; } - } - - /// - /// The list of varint values for this field. - /// - public IList VarintList - { - get { return varintList; } - } - - /// - /// The list of fixed32 values for this field. - /// - public IList Fixed32List - { - get { return fixed32List; } - } - - /// - /// The list of fixed64 values for this field. - /// - public IList Fixed64List - { - get { return fixed64List; } - } - - /// - /// The list of length-delimited values for this field. - /// - public IList LengthDelimitedList - { - get { return lengthDelimitedList; } - } - - /// - /// The list of embedded group values for this field. These - /// are represented using UnknownFieldSets rather than Messages - /// since the group's type is presumably unknown. - /// - public IList GroupList - { - get { return groupList; } - } - - public override bool Equals(object other) - { - if (ReferenceEquals(this, other)) - { - return true; - } - UnknownField otherField = other as UnknownField; - return otherField != null - && Lists.Equals(varintList, otherField.varintList) - && Lists.Equals(fixed32List, otherField.fixed32List) - && Lists.Equals(fixed64List, otherField.fixed64List) - && Lists.Equals(lengthDelimitedList, otherField.lengthDelimitedList) - && Lists.Equals(groupList, otherField.groupList); - } - - public override int GetHashCode() - { - int hash = 43; - hash = hash*47 + Lists.GetHashCode(varintList); - hash = hash*47 + Lists.GetHashCode(fixed32List); - hash = hash*47 + Lists.GetHashCode(fixed64List); - hash = hash*47 + Lists.GetHashCode(lengthDelimitedList); - hash = hash*47 + Lists.GetHashCode(groupList); - return hash; - } - - /// - /// Constructs a new Builder. - /// - public static Builder CreateBuilder() - { - return new Builder(); - } - - /// - /// Constructs a new Builder and initializes it to a copy of . - /// - public static Builder CreateBuilder(UnknownField copyFrom) - { - return new Builder().MergeFrom(copyFrom); - } - - /// - /// Serializes the field, including the field number, and writes it to - /// . - /// - public void WriteTo(int fieldNumber, ICodedOutputStream output) - { - foreach (ulong value in varintList) - { - output.WriteUnknownField(fieldNumber, WireFormat.WireType.Varint, value); - } - foreach (uint value in fixed32List) - { - output.WriteUnknownField(fieldNumber, WireFormat.WireType.Fixed32, value); - } - foreach (ulong value in fixed64List) - { - output.WriteUnknownField(fieldNumber, WireFormat.WireType.Fixed64, value); - } - foreach (ByteString value in lengthDelimitedList) - { - output.WriteUnknownBytes(fieldNumber, value); - } - foreach (UnknownFieldSet value in groupList) - { -#pragma warning disable 0612 - output.WriteUnknownGroup(fieldNumber, value); -#pragma warning restore 0612 - } - } - - /// - /// Computes the number of bytes required to encode this field, including field - /// number. - /// - public int GetSerializedSize(int fieldNumber) - { - int result = 0; - foreach (ulong value in varintList) - { - result += CodedOutputStream.ComputeUInt64Size(fieldNumber, value); - } - foreach (uint value in fixed32List) - { - result += CodedOutputStream.ComputeFixed32Size(fieldNumber, value); - } - foreach (ulong value in fixed64List) - { - result += CodedOutputStream.ComputeFixed64Size(fieldNumber, value); - } - foreach (ByteString value in lengthDelimitedList) - { - result += CodedOutputStream.ComputeBytesSize(fieldNumber, value); - } - foreach (UnknownFieldSet value in groupList) - { -#pragma warning disable 0612 - result += CodedOutputStream.ComputeUnknownGroupSize(fieldNumber, value); -#pragma warning restore 0612 - } - return result; - } - - /// - /// Serializes the length-delimited values of the field, including field - /// number, and writes them to using the MessageSet wire format. - /// - /// - /// - public void WriteAsMessageSetExtensionTo(int fieldNumber, ICodedOutputStream output) - { - foreach (ByteString value in lengthDelimitedList) - { - output.WriteMessageSetExtension(fieldNumber, UnknownFieldName, value); - } - } - - /// - /// Get the number of bytes required to encode this field, incuding field number, - /// using the MessageSet wire format. - /// - public int GetSerializedSizeAsMessageSetExtension(int fieldNumber) - { - int result = 0; - foreach (ByteString value in lengthDelimitedList) - { - result += CodedOutputStream.ComputeRawMessageSetExtensionSize(fieldNumber, value); - } - return result; - } - - /// - /// Used to build instances of UnknownField. - /// - public sealed class Builder - { - private List varintList; - private List fixed32List; - private List fixed64List; - private List lengthDelimitedList; - private List groupList; - - /// - /// Builds the field. After building, the builder is reset to an empty - /// state. (This is actually easier than making it unusable.) - /// - public UnknownField Build() - { - return new UnknownField(MakeReadOnly(ref varintList), - MakeReadOnly(ref fixed32List), - MakeReadOnly(ref fixed64List), - MakeReadOnly(ref lengthDelimitedList), - MakeReadOnly(ref groupList)); - } - - /// - /// Merge the values in into this field. For each list - /// of values, 's values are append to the ones in this - /// field. - /// - public Builder MergeFrom(UnknownField other) - { - varintList = AddAll(varintList, other.VarintList); - fixed32List = AddAll(fixed32List, other.Fixed32List); - fixed64List = AddAll(fixed64List, other.Fixed64List); - lengthDelimitedList = AddAll(lengthDelimitedList, other.LengthDelimitedList); - groupList = AddAll(groupList, other.GroupList); - return this; - } - - /// - /// Returns a new list containing all of the given specified values from - /// both the and lists. - /// If is null and is empty, - /// null is returned. Otherwise, either a new list is created (if - /// is null) or the elements of are added to . - /// - private static List AddAll(List current, IList extras) - { - if (extras.Count == 0) - { - return current; - } - if (current == null) - { - current = new List(extras); - } - else - { - current.AddRange(extras); - } - return current; - } - - /// - /// Clears the contents of this builder. - /// - public Builder Clear() - { - varintList = null; - fixed32List = null; - fixed64List = null; - lengthDelimitedList = null; - groupList = null; - return this; - } - - /// - /// Adds a varint value. - /// - public Builder AddVarint(ulong value) - { - varintList = Add(varintList, value); - return this; - } - - /// - /// Adds a fixed32 value. - /// - public Builder AddFixed32(uint value) - { - fixed32List = Add(fixed32List, value); - return this; - } - - /// - /// Adds a fixed64 value. - /// - public Builder AddFixed64(ulong value) - { - fixed64List = Add(fixed64List, value); - return this; - } - - /// - /// Adds a length-delimited value. - /// - public Builder AddLengthDelimited(ByteString value) - { - lengthDelimitedList = Add(lengthDelimitedList, value); - return this; - } - - /// - /// Adds an embedded group. - /// - /// - /// - public Builder AddGroup(UnknownFieldSet value) - { - groupList = Add(groupList, value); - return this; - } - - /// - /// Adds to the , creating - /// a new list if is null. The list is returned - either - /// the original reference or the new list. - /// - private static List Add(List list, T value) - { - if (list == null) - { - list = new List(); - } - list.Add(value); - return list; - } - - /// - /// Returns a read-only version of the given IList, and clears - /// the field used for . If the value - /// is null, an empty list is produced using Lists.Empty. - /// - /// - private static ReadOnlyCollection MakeReadOnly(ref List list) - { - ReadOnlyCollection ret = list == null ? Lists.Empty : new ReadOnlyCollection(list); - list = null; - return ret; - } - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers/UnknownFieldSet.cs b/csharp/src/ProtocolBuffers/UnknownFieldSet.cs deleted file mode 100644 index d5d0675d..00000000 --- a/csharp/src/ProtocolBuffers/UnknownFieldSet.cs +++ /dev/null @@ -1,1061 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using System.IO; -using Google.ProtocolBuffers.Collections; -using Google.ProtocolBuffers.Descriptors; - -namespace Google.ProtocolBuffers -{ - /// - /// Used to keep track of fields which were seen when parsing a protocol message - /// but whose field numbers or types are unrecognized. This most frequently - /// occurs when new fields are added to a message type and then messages containing - /// those fields are read by old software that was built before the new types were - /// added. - /// - /// Every message contains an UnknownFieldSet. - /// - /// Most users will never need to use this class directly. - /// - public sealed partial class UnknownFieldSet : IMessageLite - { - private static readonly UnknownFieldSet defaultInstance = - new UnknownFieldSet(new Dictionary()); - - private readonly IDictionary fields; - - private UnknownFieldSet(IDictionary fields) - { - this.fields = fields; - } - - /// - /// Creates a new unknown field set builder. - /// - public static Builder CreateBuilder() - { - return new Builder(); - } - - /// - /// Creates a new unknown field set builder - /// and initialize it from . - /// - public static Builder CreateBuilder(UnknownFieldSet original) - { - return new Builder().MergeFrom(original); - } - - public static UnknownFieldSet DefaultInstance - { - get { return defaultInstance; } - } - - /// - /// Returns a read-only view of the mapping from field numbers to values. - /// - public IDictionary FieldDictionary - { - get { return Dictionaries.AsReadOnly(fields); } - } - - /// - /// Checks whether or not the given field number is present in the set. - /// - public bool HasField(int field) - { - return fields.ContainsKey(field); - } - - /// - /// Fetches a field by number, returning an empty field if not present. - /// Never returns null. - /// - public UnknownField this[int number] - { - get - { - UnknownField ret; - if (!fields.TryGetValue(number, out ret)) - { - ret = UnknownField.DefaultInstance; - } - return ret; - } - } - - /// - /// Serializes the set and writes it to . - /// - public void WriteTo(ICodedOutputStream output) - { - // Avoid creating enumerator for the most common code path. - if (fields.Count > 0) - { - foreach (KeyValuePair entry in fields) - { - entry.Value.WriteTo(entry.Key, output); - } - } - } - - /// - /// Gets the number of bytes required to encode this set. - /// - public int SerializedSize - { - get - { - // Avoid creating enumerator for the most common code path. - if (fields.Count == 0) - { - return 0; - } - - int result = 0; - foreach (KeyValuePair entry in fields) - { - result += entry.Value.GetSerializedSize(entry.Key); - } - return result; - } - } - - /// - /// Converts the set to a string in protocol buffer text format. This - /// is just a trivial wrapper around TextFormat.PrintToString. - /// - public override String ToString() - { - return TextFormat.PrintToString(this); - } - - /// - /// Converts the set to a string in protocol buffer text format. This - /// is just a trivial wrapper around TextFormat.PrintToString. - /// - public void PrintTo(TextWriter writer) - { - TextFormat.Print(this, writer); - } - - /// - /// Serializes the message to a ByteString and returns it. This is - /// just a trivial wrapper around WriteTo(ICodedOutputStream). - /// - /// - public ByteString ToByteString() - { - ByteString.CodedBuilder codedBuilder = new ByteString.CodedBuilder(SerializedSize); - WriteTo(codedBuilder.CodedOutput); - return codedBuilder.Build(); - } - - /// - /// Serializes the message to a byte array and returns it. This is - /// just a trivial wrapper around WriteTo(ICodedOutputStream). - /// - /// - public byte[] ToByteArray() - { - byte[] data = new byte[SerializedSize]; - CodedOutputStream output = CodedOutputStream.CreateInstance(data); - WriteTo(output); - output.CheckNoSpaceLeft(); - return data; - } - - /// - /// Serializes the message and writes it to . This is - /// just a trivial wrapper around WriteTo(ICodedOutputStream). - /// - /// - public void WriteTo(Stream output) - { - CodedOutputStream codedOutput = CodedOutputStream.CreateInstance(output); - WriteTo(codedOutput); - codedOutput.Flush(); - } - - /// - /// Serializes the set and writes it to using - /// the MessageSet wire format. - /// - public void WriteAsMessageSetTo(ICodedOutputStream output) - { - // Avoid creating enumerator for the most common code path. - if (fields.Count > 0) - { - foreach (KeyValuePair entry in fields) - { - entry.Value.WriteAsMessageSetExtensionTo(entry.Key, output); - } - } - } - - /// - /// Gets the number of bytes required to encode this set using the MessageSet - /// wire format. - /// - public int SerializedSizeAsMessageSet - { - get - { - // Avoid creating enumerator for the most common code path. - if (fields.Count == 0) - { - return 0; - } - - int result = 0; - foreach (KeyValuePair entry in fields) - { - result += entry.Value.GetSerializedSizeAsMessageSetExtension(entry.Key); - } - return result; - } - } - - public override bool Equals(object other) - { - if (ReferenceEquals(this, other)) - { - return true; - } - UnknownFieldSet otherSet = other as UnknownFieldSet; - return otherSet != null && Dictionaries.Equals(fields, otherSet.fields); - } - - public override int GetHashCode() - { - return Dictionaries.GetHashCode(fields); - } - - /// - /// Parses an UnknownFieldSet from the given input. - /// - public static UnknownFieldSet ParseFrom(ICodedInputStream input) - { - return CreateBuilder().MergeFrom(input).Build(); - } - - /// - /// Parses an UnknownFieldSet from the given data. - /// - public static UnknownFieldSet ParseFrom(ByteString data) - { - return CreateBuilder().MergeFrom(data).Build(); - } - - /// - /// Parses an UnknownFieldSet from the given data. - /// - public static UnknownFieldSet ParseFrom(byte[] data) - { - return CreateBuilder().MergeFrom(data).Build(); - } - - /// - /// Parses an UnknownFieldSet from the given input. - /// - public static UnknownFieldSet ParseFrom(Stream input) - { - return CreateBuilder().MergeFrom(input).Build(); - } - - #region IMessageLite Members - - public bool IsInitialized - { - get { return fields != null; } - } - - public void WriteDelimitedTo(Stream output) - { - CodedOutputStream codedOutput = CodedOutputStream.CreateInstance(output); - codedOutput.WriteRawVarint32((uint) SerializedSize); - WriteTo(codedOutput); - codedOutput.Flush(); - } - - public IBuilderLite WeakCreateBuilderForType() - { - return new Builder(); - } - - public IBuilderLite WeakToBuilder() - { - return new Builder(fields); - } - - public IMessageLite WeakDefaultInstanceForType - { - get { return defaultInstance; } - } - - #endregion - - /// - /// Builder for UnknownFieldSets. - /// - public sealed partial class Builder : IBuilderLite - { - /// - /// Mapping from number to field. Note that by using a SortedList we ensure - /// that the fields will be serialized in ascending order. - /// - private IDictionary fields; - - // Optimization: We keep around a builder for the last field that was - // modified so that we can efficiently add to it multiple times in a - // row (important when parsing an unknown repeated field). - private int lastFieldNumber; - private UnknownField.Builder lastField; - - internal Builder() - { - fields = new SortedDictionary(); - } - - internal Builder(IDictionary dictionary) - { - fields = new SortedDictionary(dictionary); - } - - /// - /// Returns a field builder for the specified field number, including any values - /// which already exist. - /// - private UnknownField.Builder GetFieldBuilder(int number) - { - if (lastField != null) - { - if (number == lastFieldNumber) - { - return lastField; - } - // Note: AddField() will reset lastField and lastFieldNumber. - AddField(lastFieldNumber, lastField.Build()); - } - if (number == 0) - { - return null; - } - - lastField = UnknownField.CreateBuilder(); - UnknownField existing; - if (fields.TryGetValue(number, out existing)) - { - lastField.MergeFrom(existing); - } - lastFieldNumber = number; - return lastField; - } - - /// - /// Build the UnknownFieldSet and return it. Once this method has been called, - /// this instance will no longer be usable. Calling any method after this - /// will throw a NullReferenceException. - /// - public UnknownFieldSet Build() - { - GetFieldBuilder(0); // Force lastField to be built. - UnknownFieldSet result = fields.Count == 0 ? DefaultInstance : new UnknownFieldSet(fields); - fields = null; - return result; - } - - /// - /// Adds a field to the set. If a field with the same number already exists, it - /// is replaced. - /// - public Builder AddField(int number, UnknownField field) - { - if (number == 0) - { - throw new ArgumentOutOfRangeException("number", "Zero is not a valid field number."); - } - if (lastField != null && lastFieldNumber == number) - { - // Discard this. - lastField = null; - lastFieldNumber = 0; - } - fields[number] = field; - return this; - } - - /// - /// Resets the builder to an empty set. - /// - public Builder Clear() - { - fields.Clear(); - lastFieldNumber = 0; - lastField = null; - return this; - } - - /// - /// Parse an entire message from and merge - /// its fields into this set. - /// - public Builder MergeFrom(ICodedInputStream input) - { - uint tag; - string name; - while (input.ReadTag(out tag, out name)) - { - if (tag == 0) - { - if (input.SkipField()) - { - continue; //can't merge unknown without field tag - } - break; - } - - if (!MergeFieldFrom(tag, input)) - { - break; - } - } - return this; - } - - /// - /// Parse a single field from and merge it - /// into this set. - /// - /// The field's tag number, which was already parsed. - /// The coded input stream containing the field - /// false if the tag is an "end group" tag, true otherwise - public bool MergeFieldFrom(uint tag, ICodedInputStream input) - { - if (tag == 0) - { - input.SkipField(); - return true; - } - - int number = WireFormat.GetTagFieldNumber(tag); - switch (WireFormat.GetTagWireType(tag)) - { - case WireFormat.WireType.Varint: - { - ulong uint64 = 0; - if (input.ReadUInt64(ref uint64)) - { - GetFieldBuilder(number).AddVarint(uint64); - } - return true; - } - case WireFormat.WireType.Fixed32: - { - uint uint32 = 0; - if (input.ReadFixed32(ref uint32)) - { - GetFieldBuilder(number).AddFixed32(uint32); - } - return true; - } - case WireFormat.WireType.Fixed64: - { - ulong uint64 = 0; - if (input.ReadFixed64(ref uint64)) - { - GetFieldBuilder(number).AddFixed64(uint64); - } - return true; - } - case WireFormat.WireType.LengthDelimited: - { - ByteString bytes = null; - if (input.ReadBytes(ref bytes)) - { - GetFieldBuilder(number).AddLengthDelimited(bytes); - } - return true; - } - case WireFormat.WireType.StartGroup: - { - Builder subBuilder = CreateBuilder(); -#pragma warning disable 0612 - input.ReadUnknownGroup(number, subBuilder); -#pragma warning restore 0612 - GetFieldBuilder(number).AddGroup(subBuilder.Build()); - return true; - } - case WireFormat.WireType.EndGroup: - return false; - default: - throw InvalidProtocolBufferException.InvalidWireType(); - } - } - - /// - /// Parses as an UnknownFieldSet and merge it - /// with the set being built. This is just a small wrapper around - /// MergeFrom(ICodedInputStream). - /// - public Builder MergeFrom(Stream input) - { - CodedInputStream codedInput = CodedInputStream.CreateInstance(input); - MergeFrom(codedInput); - codedInput.CheckLastTagWas(0); - return this; - } - - /// - /// Parses as an UnknownFieldSet and merge it - /// with the set being built. This is just a small wrapper around - /// MergeFrom(ICodedInputStream). - /// - public Builder MergeFrom(ByteString data) - { - CodedInputStream input = data.CreateCodedInput(); - MergeFrom(input); - input.CheckLastTagWas(0); - return this; - } - - /// - /// Parses as an UnknownFieldSet and merge it - /// with the set being built. This is just a small wrapper around - /// MergeFrom(ICodedInputStream). - /// - public Builder MergeFrom(byte[] data) - { - CodedInputStream input = CodedInputStream.CreateInstance(data); - MergeFrom(input); - input.CheckLastTagWas(0); - return this; - } - - /// - /// Convenience method for merging a new field containing a single varint - /// value. This is used in particular when an unknown enum value is - /// encountered. - /// - public Builder MergeVarintField(int number, ulong value) - { - if (number == 0) - { - throw new ArgumentOutOfRangeException("number", "Zero is not a valid field number."); - } - GetFieldBuilder(number).AddVarint(value); - return this; - } - - /// - /// Merges the fields from into this set. - /// If a field number exists in both sets, the values in - /// will be appended to the values in this set. - /// - public Builder MergeFrom(UnknownFieldSet other) - { - if (other != DefaultInstance) - { - foreach (KeyValuePair entry in other.fields) - { - MergeField(entry.Key, entry.Value); - } - } - return this; - } - - /// - /// Checks if the given field number is present in the set. - /// - public bool HasField(int number) - { - if (number == 0) - { - throw new ArgumentOutOfRangeException("number", "Zero is not a valid field number."); - } - return number == lastFieldNumber || fields.ContainsKey(number); - } - - /// - /// Adds a field to the unknown field set. If a field with the same - /// number already exists, the two are merged. - /// - public Builder MergeField(int number, UnknownField field) - { - if (number == 0) - { - throw new ArgumentOutOfRangeException("number", "Zero is not a valid field number."); - } - if (HasField(number)) - { - GetFieldBuilder(number).MergeFrom(field); - } - else - { - // Optimization: We could call getFieldBuilder(number).mergeFrom(field) - // in this case, but that would create a copy of the Field object. - // We'd rather reuse the one passed to us, so call AddField() instead. - AddField(number, field); - } - return this; - } - - internal void MergeFrom(ICodedInputStream input, ExtensionRegistry extensionRegistry, IBuilder builder) - { - uint tag; - string name; - while (input.ReadTag(out tag, out name)) - { - if (tag == 0 && name != null) - { - FieldDescriptor fieldByName = builder.DescriptorForType.FindFieldByName(name); - if (fieldByName != null) - { - tag = WireFormat.MakeTag(fieldByName); - } - else - { - ExtensionInfo extension = extensionRegistry.FindByName(builder.DescriptorForType, name); - if (extension != null) - { - tag = WireFormat.MakeTag(extension.Descriptor); - } - } - } - if (tag == 0) - { - if (input.SkipField()) - { - continue; //can't merge unknown without field tag - } - break; - } - - if (!MergeFieldFrom(input, extensionRegistry, builder, tag, name)) - { - // end group tag - break; - } - } - } - - /// - /// Like - /// but parses a single field. - /// - /// The input to read the field from - /// Registry to use when an extension field is encountered - /// Builder to merge field into, if it's a known field - /// The tag, which should already have been read from the input - /// true unless the tag is an end-group tag - internal bool MergeFieldFrom(ICodedInputStream input, - ExtensionRegistry extensionRegistry, IBuilder builder, uint tag, - string fieldName) - { - if (tag == 0 && fieldName != null) - { - FieldDescriptor fieldByName = builder.DescriptorForType.FindFieldByName(fieldName); - if (fieldByName != null) - { - tag = WireFormat.MakeTag(fieldByName); - } - else - { - ExtensionInfo extension = extensionRegistry.FindByName(builder.DescriptorForType, fieldName); - if (extension != null) - { - tag = WireFormat.MakeTag(extension.Descriptor); - } - } - } - - MessageDescriptor type = builder.DescriptorForType; - if (type.Options.MessageSetWireFormat && tag == WireFormat.MessageSetTag.ItemStart) - { - MergeMessageSetExtensionFromCodedStream(input, extensionRegistry, builder); - return true; - } - - WireFormat.WireType wireType = WireFormat.GetTagWireType(tag); - int fieldNumber = WireFormat.GetTagFieldNumber(tag); - - FieldDescriptor field; - IMessageLite defaultFieldInstance = null; - - if (type.IsExtensionNumber(fieldNumber)) - { - ExtensionInfo extension = extensionRegistry[type, fieldNumber]; - if (extension == null) - { - field = null; - } - else - { - field = extension.Descriptor; - defaultFieldInstance = extension.DefaultInstance; - } - } - else - { - field = type.FindFieldByNumber(fieldNumber); - } - - // Unknown field or wrong wire type. Skip. - if (field == null) - { - return MergeFieldFrom(tag, input); - } - if (wireType != WireFormat.GetWireType(field)) - { - WireFormat.WireType expectedType = WireFormat.GetWireType(field.FieldType); - if (wireType == expectedType) - { - //Allowed as of 2.3, this is unpacked data for a packed array - } - else if (field.IsRepeated && wireType == WireFormat.WireType.LengthDelimited && - (expectedType == WireFormat.WireType.Varint || expectedType == WireFormat.WireType.Fixed32 || - expectedType == WireFormat.WireType.Fixed64)) - { - //Allowed as of 2.3, this is packed data for an unpacked array - } - else - { - return MergeFieldFrom(tag, input); - } - } - - switch (field.FieldType) - { - case FieldType.Group: - case FieldType.Message: - { - IBuilderLite subBuilder = (defaultFieldInstance != null) - ? defaultFieldInstance.WeakCreateBuilderForType() - : builder.CreateBuilderForField(field); - if (!field.IsRepeated) - { - subBuilder.WeakMergeFrom((IMessageLite) builder[field]); - if (field.FieldType == FieldType.Group) - { - input.ReadGroup(field.FieldNumber, subBuilder, extensionRegistry); - } - else - { - input.ReadMessage(subBuilder, extensionRegistry); - } - builder[field] = subBuilder.WeakBuild(); - } - else - { - List list = new List(); - if (field.FieldType == FieldType.Group) - { - input.ReadGroupArray(tag, fieldName, list, subBuilder.WeakDefaultInstanceForType, - extensionRegistry); - } - else - { - input.ReadMessageArray(tag, fieldName, list, subBuilder.WeakDefaultInstanceForType, - extensionRegistry); - } - - foreach (IMessageLite m in list) - { - builder.WeakAddRepeatedField(field, m); - } - return true; - } - break; - } - case FieldType.Enum: - { - if (!field.IsRepeated) - { - object unknown; - IEnumLite value = null; - if (input.ReadEnum(ref value, out unknown, field.EnumType)) - { - builder[field] = value; - } - else if (unknown is int) - { - MergeVarintField(fieldNumber, (ulong) (int) unknown); - } - } - else - { - ICollection unknown; - List list = new List(); - input.ReadEnumArray(tag, fieldName, list, out unknown, field.EnumType); - - foreach (IEnumLite en in list) - { - builder.WeakAddRepeatedField(field, en); - } - - if (unknown != null) - { - foreach (object oval in unknown) - { - if (oval is int) - { - MergeVarintField(fieldNumber, (ulong) (int) oval); - } - } - } - } - break; - } - default: - { - if (!field.IsRepeated) - { - object value = null; - if (input.ReadPrimitiveField(field.FieldType, ref value)) - { - builder[field] = value; - } - } - else - { - List list = new List(); - input.ReadPrimitiveArray(field.FieldType, tag, fieldName, list); - foreach (object oval in list) - { - builder.WeakAddRepeatedField(field, oval); - } - } - break; - } - } - return true; - } - - /// - /// Called by MergeFieldFrom to parse a MessageSet extension. - /// - private void MergeMessageSetExtensionFromCodedStream(ICodedInputStream input, - ExtensionRegistry extensionRegistry, IBuilder builder) - { - MessageDescriptor type = builder.DescriptorForType; - - // The wire format for MessageSet is: - // message MessageSet { - // repeated group Item = 1 { - // required int32 typeId = 2; - // required bytes message = 3; - // } - // } - // "typeId" is the extension's field number. The extension can only be - // a message type, where "message" contains the encoded bytes of that - // message. - // - // In practice, we will probably never see a MessageSet item in which - // the message appears before the type ID, or where either field does not - // appear exactly once. However, in theory such cases are valid, so we - // should be prepared to accept them. - - int typeId = 0; - ByteString rawBytes = null; // If we encounter "message" before "typeId" - IBuilderLite subBuilder = null; - FieldDescriptor field = null; - - uint lastTag = WireFormat.MessageSetTag.ItemStart; - uint tag; - string name; - while (input.ReadTag(out tag, out name)) - { - if (tag == 0 && name != null) - { - if (name == "type_id") - { - tag = WireFormat.MessageSetTag.TypeID; - } - else if (name == "message") - { - tag = WireFormat.MessageSetTag.Message; - } - } - if (tag == 0) - { - if (input.SkipField()) - { - continue; //can't merge unknown without field tag - } - break; - } - - lastTag = tag; - if (tag == WireFormat.MessageSetTag.TypeID) - { - typeId = 0; - // Zero is not a valid type ID. - if (input.ReadInt32(ref typeId) && typeId != 0) - { - ExtensionInfo extension = extensionRegistry[type, typeId]; - if (extension != null) - { - field = extension.Descriptor; - subBuilder = extension.DefaultInstance.WeakCreateBuilderForType(); - IMessageLite originalMessage = (IMessageLite) builder[field]; - if (originalMessage != null) - { - subBuilder.WeakMergeFrom(originalMessage); - } - if (rawBytes != null) - { - // We already encountered the message. Parse it now. - // TODO(jonskeet): Check this is okay. It's subtly different from the Java, as it doesn't create an input stream from rawBytes. - // In fact, why don't we just call MergeFrom(rawBytes)? And what about the extension registry? - subBuilder.WeakMergeFrom(rawBytes.CreateCodedInput()); - rawBytes = null; - } - } - else - { - // Unknown extension number. If we already saw data, put it - // in rawBytes. - if (rawBytes != null) - { - MergeField(typeId, UnknownField.CreateBuilder().AddLengthDelimited(rawBytes).Build()); - rawBytes = null; - } - } - } - } - else if (tag == WireFormat.MessageSetTag.Message) - { - if (subBuilder != null) - { - // We already know the type, so we can parse directly from the input - // with no copying. Hooray! - input.ReadMessage(subBuilder, extensionRegistry); - } - else if (input.ReadBytes(ref rawBytes)) - { - if (typeId != 0) - { - // We don't know how to parse this. Ignore it. - MergeField(typeId, - UnknownField.CreateBuilder().AddLengthDelimited(rawBytes).Build()); - } - } - } - else - { - // Unknown tag. Skip it. - if (!input.SkipField()) - { - break; // end of group - } - } - } - - if (lastTag != WireFormat.MessageSetTag.ItemEnd) - { - throw InvalidProtocolBufferException.InvalidEndTag(); - } - - if (subBuilder != null) - { - builder[field] = subBuilder.WeakBuild(); - } - } - - #region IBuilderLite Members - - bool IBuilderLite.IsInitialized - { - get { return fields != null; } - } - - IBuilderLite IBuilderLite.WeakClear() - { - return Clear(); - } - - IBuilderLite IBuilderLite.WeakMergeFrom(IMessageLite message) - { - return MergeFrom((UnknownFieldSet) message); - } - - IBuilderLite IBuilderLite.WeakMergeFrom(ByteString data) - { - return MergeFrom(data); - } - - IBuilderLite IBuilderLite.WeakMergeFrom(ByteString data, ExtensionRegistry registry) - { - return MergeFrom(data); - } - - IBuilderLite IBuilderLite.WeakMergeFrom(ICodedInputStream input) - { - return MergeFrom(input); - } - - IBuilderLite IBuilderLite.WeakMergeFrom(ICodedInputStream input, ExtensionRegistry registry) - { - return MergeFrom(input); - } - - IMessageLite IBuilderLite.WeakBuild() - { - return Build(); - } - - IMessageLite IBuilderLite.WeakBuildPartial() - { - return Build(); - } - - IBuilderLite IBuilderLite.WeakClone() - { - return Build().WeakToBuilder(); - } - - IMessageLite IBuilderLite.WeakDefaultInstanceForType - { - get { return DefaultInstance; } - } - - #endregion - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers/WireFormat.cs b/csharp/src/ProtocolBuffers/WireFormat.cs index b9daa328..87f7c358 100644 --- a/csharp/src/ProtocolBuffers/WireFormat.cs +++ b/csharp/src/ProtocolBuffers/WireFormat.cs @@ -35,9 +35,9 @@ #endregion using System; -using Google.ProtocolBuffers.Descriptors; +using Google.Protobuf.Descriptors; -namespace Google.ProtocolBuffers +namespace Google.Protobuf { /// /// This class is used internally by the Protocol Buffer Library and generated diff --git a/src/google/protobuf/compiler/csharp/csharp_enum_field.cc b/src/google/protobuf/compiler/csharp/csharp_enum_field.cc index 8865702d..ee9d6a1d 100644 --- a/src/google/protobuf/compiler/csharp/csharp_enum_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_enum_field.cc @@ -61,7 +61,7 @@ void EnumFieldGenerator::GenerateParsingCode(io::Printer* printer) { void EnumFieldGenerator::GenerateSerializationCode(io::Printer* printer) { printer->Print(variables_, "if ($has_property_check$) {\n" - " output.WriteEnum($number$, fieldNames[$field_ordinal$], (long) $property_name$, $property_name$);\n" + " output.WriteEnum($number$, fieldNames[$field_ordinal$], $property_name$);\n" "}\n"); } @@ -69,7 +69,7 @@ void EnumFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { printer->Print( variables_, "if ($has_property_check$) {\n" - " size += pb::CodedOutputStream.ComputeEnumSize($number$, (long) $property_name$);\n" + " size += pb::CodedOutputStream.ComputeEnumSize($number$, $property_name$);\n" "}\n"); } @@ -87,8 +87,8 @@ void EnumOneofFieldGenerator::GenerateParsingCode(io::Printer* printer) { variables_, "$type_name$ enumValue = $default_value$;\n" "if(input.ReadEnum(ref enumValue)) {\n" - " result.$oneof_name$_ = enumValue;\n" - " result.$oneof_name$Case_ = $oneof_property_name$OneofCase.$property_name$;\n" + " $oneof_name$_ = enumValue;\n" + " $oneof_name$Case_ = $oneof_property_name$OneofCase.$property_name$;\n" "}\n"); } diff --git a/src/google/protobuf/compiler/csharp/csharp_field_base.cc b/src/google/protobuf/compiler/csharp/csharp_field_base.cc index 367e54c2..ec0d51ca 100644 --- a/src/google/protobuf/compiler/csharp/csharp_field_base.cc +++ b/src/google/protobuf/compiler/csharp/csharp_field_base.cc @@ -38,6 +38,7 @@ #include #include #include +#include #include #include @@ -51,6 +52,11 @@ namespace csharp { void FieldGeneratorBase::SetCommonFieldVariables( map* variables) { + // Note: this will be valid even though the tag emitted for packed and unpacked versions of + // repeated fields varies by wire format. The wire format is encoded in the bottom 3 bits, which + // never effects the tag size. + int tagSize = internal::WireFormat::TagSize(descriptor_->number(), descriptor_->type()); + (*variables)["tag_size"] = SimpleItoa(tagSize); (*variables)["property_name"] = property_name(); (*variables)["type_name"] = type_name(); (*variables)["name"] = name(); @@ -65,15 +71,10 @@ void FieldGeneratorBase::SetCommonFieldVariables( (*variables)["capitalized_type_name"] = capitalized_type_name(); (*variables)["number"] = number(); (*variables)["field_ordinal"] = field_ordinal(); - if (SupportFieldPresence(descriptor_->file())) { - (*variables)["has_property_check"] = "has" + (*variables)["property_name"]; - (*variables)["other_has_property_check"] = "other.Has" + (*variables)["property_name"]; - } else { - (*variables)["has_property_check"] = - (*variables)["property_name"] + " != " + (*variables)["default_value"]; - (*variables)["other_has_property_check"] = "other." + - (*variables)["property_name"] + " != " + (*variables)["default_value"]; - } + (*variables)["has_property_check"] = + (*variables)["property_name"] + " != " + (*variables)["default_value"]; + (*variables)["other_has_property_check"] = "other." + + (*variables)["property_name"] + " != " + (*variables)["default_value"]; } void FieldGeneratorBase::SetCommonOneofFieldVariables( diff --git a/src/google/protobuf/compiler/csharp/csharp_message.cc b/src/google/protobuf/compiler/csharp/csharp_message.cc index 1defcf94..b5929bcd 100644 --- a/src/google/protobuf/compiler/csharp/csharp_message.cc +++ b/src/google/protobuf/compiler/csharp/csharp_message.cc @@ -179,10 +179,14 @@ void MessageGenerator::Generate(io::Printer* printer) { WriteGeneratedCodeAttributes(printer); printer->Print( vars, - "$access_level$ sealed partial class $class_name$ : pb::IMessage<$class_name$> {\n"); + "$access_level$ sealed partial class $class_name$ : pb::IMessage<$class_name$>, global::System.IEquatable<$class_name$> {\n"); printer->Indent(); // All static fields and properties + printer->Print( + vars, + "private static readonly pb::MessageParser<$class_name$> _parser = new pb::MessageParser<$class_name$>(() => new $class_name$());\n" + "public static pb::MessageParser<$class_name$> Parser { get { return _parser; } }\n\n"); printer->Print( "private static readonly string[] _fieldNames = " "new string[] { $slash$$field_names$$slash$ };\n", @@ -204,7 +208,7 @@ void MessageGenerator::Generate(io::Printer* printer) { " get { return $umbrella_class_name$.internal__$identifier$__Descriptor; }\n" "}\n" "\n" - "protected override pb::FieldAccess.FieldAccessorTable<$class_name$> InternalFieldAccessors {\n" + "public pb::FieldAccess.FieldAccessorTable<$class_name$> Fields {\n" " get { return $umbrella_class_name$.internal__$identifier$__FieldAccessorTable; }\n" "}\n" "\n"); @@ -217,7 +221,7 @@ void MessageGenerator::Generate(io::Printer* printer) { printer->Print( vars, "public $class_name$($class_name$ other) {\n" - " MergeWith(other);\n" + " MergeFrom(other);\n" "}\n"); // Merge ctor. // Fields/properties @@ -259,15 +263,16 @@ void MessageGenerator::Generate(io::Printer* printer) { "public $property_name$OneofCase $property_name$Case {\n" " get { return $name$Case_; }\n" "}\n\n" - "private Clear$property_name$() {;\n" - " $name$Case_ = $property_name$OneofCase.None;" - " $name$_ = null;" + "public void Clear$property_name$() {\n" + " $name$Case_ = $property_name$OneofCase.None;\n" + " $name$_ = null;\n" "}\n\n"); } // TODO(jonskeet): Map properties // Standard methods + GenerateFrameworkMethods(printer); GenerateMessageSerializationMethods(printer); GenerateMergingMethods(printer); @@ -298,6 +303,51 @@ void MessageGenerator::Generate(io::Printer* printer) { } +void MessageGenerator::GenerateFrameworkMethods(io::Printer* printer) { + map vars; + vars["class_name"] = class_name(); + + // Equality + printer->Print( + vars, + "public override bool Equals(object other) {\n" + " return Equals(other as $class_name$);\n" + "}\n\n" + "public bool Equals($class_name$ other) {\n" + " if (ReferenceEquals(other, null)) {\n" + " return false;\n" + " }\n" + " if (ReferenceEquals(other, this)) {\n" + " return true;\n" + " }\n"); + printer->Indent(); + for (int i = 0; i < descriptor_->field_count(); i++) { + scoped_ptr generator( + CreateFieldGeneratorInternal(descriptor_->field(i))); + generator->WriteEquals(printer); + } + printer->Outdent(); + printer->Print( + " return true;\n" + "}\n\n"); + + // GetHashCode + printer->Print( + "public override int GetHashCode() {\n" + " int hash = 0;\n"); + printer->Indent(); + for (int i = 0; i < descriptor_->field_count(); i++) { + scoped_ptr generator( + CreateFieldGeneratorInternal(descriptor_->field(i))); + generator->WriteHash(printer); + } + printer->Print("return hash;\n"); + printer->Outdent(); + printer->Print("}\n\n"); + + // TODO(jonskeet): ToString. +} + void MessageGenerator::GenerateMessageSerializationMethods(io::Printer* printer) { printer->Print( "public void WriteTo(pb::ICodedOutputStream output) {\n"); @@ -316,7 +366,7 @@ void MessageGenerator::GenerateMessageSerializationMethods(io::Printer* printer) printer->Print( "}\n" "\n" - "public int CalculateSerializedSize() {\n"); + "public int CalculateSize() {\n"); printer->Indent(); printer->Print("int size = 0;\n"); for (int i = 0; i < descriptor_->field_count(); i++) { @@ -338,7 +388,7 @@ void MessageGenerator::GenerateMergingMethods(io::Printer* printer) { printer->Print( vars, - "public void MergeWith($class_name$ other) {\n"); + "public void MergeFrom($class_name$ other) {\n"); printer->Indent(); printer->Print( "if (other == null) {\n" @@ -378,39 +428,38 @@ void MessageGenerator::GenerateMergingMethods(io::Printer* printer) { printer->Print( "uint tag;\n" "string fieldName;\n" - "while (input.ReadTag(out tag, out fieldName)) {\n" - " if (tag == 0 && fieldName != null) {"); - printer->Indent(); + "while (input.ReadTag(out tag, out fieldName)) {\n"); printer->Indent(); printer->Print( - "int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.String.String.Ordinal);\n" - "if (fieldOrdinal >= 0) {\n" - " tag = _fieldTags[fieldOrdinal];\n" + "if (tag == 0 && fieldName != null) {\n" + " int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal);\n" + " if (fieldOrdinal >= 0) {\n" + " tag = _fieldTags[fieldOrdinal];\n" + " }\n" "}\n" "switch(tag) {\n"); printer->Indent(); printer->Print( - "case 0: {\n" // 0 signals EOF / limit reached + "case 0:\n" // 0 signals EOF / limit reached " throw pb::InvalidProtocolBufferException.InvalidTag();\n" - "}\n" "default:\n" " if (pb::WireFormat.IsEndGroupTag(tag)) {\n" " return;\n" " }\n" - " break;"); // Note: we're ignoring unknown fields here. + " break;\n"); // Note: we're ignoring unknown fields here. for (int i = 0; i < fields_by_number().size(); i++) { const FieldDescriptor* field = fields_by_number()[i]; internal::WireFormatLite::WireType wt = internal::WireFormat::WireTypeForFieldType(field->type()); uint32 tag = internal::WireFormatLite::MakeTag(field->number(), wt); - // TODO(jonskeet): Understand what this is trying to do - if (field->is_repeated() - && (wt == internal::WireFormatLite::WIRETYPE_VARINT - || wt == internal::WireFormatLite::WIRETYPE_FIXED32 - || wt == internal::WireFormatLite::WIRETYPE_FIXED64)) { + // Handle both packed and unpacked repeated fields with the same Read*Array call; + // the two generated cases are the packed and unpacked tags. + // TODO(jonskeet): Check that is_packable is equivalent to is_repeated && wt in { VARINT, FIXED32, FIXED64 }. + // It looks like it is... + if (field->is_packable()) { printer->Print( - "case $number$:\n", - "number", + "case $packed_tag$:\n", + "packed_tag", SimpleItoa( internal::WireFormatLite::MakeTag( field->number(), @@ -429,8 +478,6 @@ void MessageGenerator::GenerateMergingMethods(io::Printer* printer) { printer->Outdent(); printer->Print("}\n"); // switch printer->Outdent(); - printer->Print("}\n"); // if - printer->Outdent(); printer->Print("}\n"); // while printer->Outdent(); printer->Print("}\n\n"); // method diff --git a/src/google/protobuf/compiler/csharp/csharp_message.h b/src/google/protobuf/compiler/csharp/csharp_message.h index f5f41c73..eb90ce67 100644 --- a/src/google/protobuf/compiler/csharp/csharp_message.h +++ b/src/google/protobuf/compiler/csharp/csharp_message.h @@ -50,6 +50,7 @@ class MessageGenerator : public SourceGeneratorBase { MessageGenerator(const Descriptor* descriptor); ~MessageGenerator(); + void GenerateFrameworkMethods(io::Printer* printer); void GenerateStaticVariables(io::Printer* printer); void GenerateStaticVariableInitializers(io::Printer* printer); void Generate(io::Printer* printer); diff --git a/src/google/protobuf/compiler/csharp/csharp_message_field.cc b/src/google/protobuf/compiler/csharp/csharp_message_field.cc index 90aa201b..4b7ac88f 100644 --- a/src/google/protobuf/compiler/csharp/csharp_message_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_message_field.cc @@ -49,8 +49,8 @@ namespace csharp { MessageFieldGenerator::MessageFieldGenerator(const FieldDescriptor* descriptor, int fieldOrdinal) : FieldGeneratorBase(descriptor, fieldOrdinal) { - variables_["has_property_check"] = property_name() + "_ != null"; - variables_["has_not_property_check"] = property_name() + "_ == null"; + variables_["has_property_check"] = name() + "_ != null"; + variables_["has_not_property_check"] = name() + "_ == null"; } MessageFieldGenerator::~MessageFieldGenerator() { @@ -66,7 +66,7 @@ void MessageFieldGenerator::GenerateMembers(io::Printer* printer) { variables_, "public $type_name$ $property_name$ {\n" " get { return $name$_; }\n" - " set { return $name$_ = value; }\n" + " set { $name$_ = value; }\n" "}\n"); } @@ -74,17 +74,17 @@ void MessageFieldGenerator::GenerateMergingCode(io::Printer* printer) { printer->Print( variables_, "if (other.$has_property_check$) {\n" - " if ($has_not_property_check) {\n" + " if ($has_not_property_check$) {\n" " $name$_ = new $type_name$();\n" " }\n" - " $property_name$.MergeWith(other.$property_name);\n" + " $property_name$.MergeFrom(other.$property_name$);\n" "}\n"); } void MessageFieldGenerator::GenerateParsingCode(io::Printer* printer) { printer->Print( variables_, - "if ($has_not_property_check) {\n" + "if ($has_not_property_check$) {\n" " $name$_ = new $type_name$();\n" "}\n" "input.ReadMessage($name$_);\n"); // No need to support TYPE_GROUP... @@ -110,12 +110,12 @@ void MessageFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { void MessageFieldGenerator::WriteHash(io::Printer* printer) { printer->Print( variables_, - "if ($has_property_check$) hash ^= $name$_.GetHashCode();\n"); + "if ($has_property_check$) hash ^= $property_name$.GetHashCode();\n"); } void MessageFieldGenerator::WriteEquals(io::Printer* printer) { printer->Print( variables_, - "if (!object.Equals($property_name$_, other.$property_name$_)) return false;\n"); + "if (!object.Equals($property_name$, other.$property_name$)) return false;"); } void MessageFieldGenerator::WriteToString(io::Printer* printer) { variables_["field_name"] = GetFieldName(descriptor_); @@ -140,10 +140,10 @@ void MessageOneofFieldGenerator::GenerateMembers(io::Printer* printer) { variables_, "public $type_name$ $property_name$ {\n" " get { return $has_property_check$ ? ($type_name$) $oneof_name$_ : null; }\n" - " set { \n" - " $name$_ = value;" - " $oneof_name$Case_ = value == null ? $oneof_property_name$Case.None : $oneof_property_name$Case.$property_name$; }\n" - " } \n" + " set {\n" + " $oneof_name$_ = value;\n" + " $oneof_name$Case_ = value == null ? $oneof_property_name$OneofCase.None : $oneof_property_name$OneofCase.$property_name$;\n" + " }\n" "}\n"); } @@ -151,12 +151,12 @@ void MessageOneofFieldGenerator::GenerateParsingCode(io::Printer* printer) { // TODO(jonskeet): We may be able to do better than this printer->Print( variables_, - "$type_name$ subBuilder = new type_name$();\n" + "$type_name$ subBuilder = new $type_name$();\n" "if ($has_property_check$) {\n" - " subBuilder.MergeWith($property_name$);\n" + " subBuilder.MergeFrom($property_name$);\n" "}\n" "input.ReadMessage(subBuilder);\n" // No support of TYPE_GROUP - "$oneof_property_name$ = subBuilder;\n"); + "$property_name$ = subBuilder;\n"); } void MessageOneofFieldGenerator::WriteToString(io::Printer* printer) { diff --git a/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc b/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc index bc4858fc..f2b66a00 100644 --- a/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc @@ -93,7 +93,7 @@ void PrimitiveFieldGenerator::GenerateMergingCode(io::Printer* printer) { void PrimitiveFieldGenerator::GenerateParsingCode(io::Printer* printer) { printer->Print( variables_, - "input.Read$capitalized_type_name$(ref result.$name$_);\n"); + "input.Read$capitalized_type_name$(ref $name$_);\n"); } void PrimitiveFieldGenerator::GenerateSerializationCode(io::Printer* printer) { @@ -115,9 +115,7 @@ void PrimitiveFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { void PrimitiveFieldGenerator::WriteHash(io::Printer* printer) { printer->Print( variables_, - "if ($has_property_check$) {\n" - " hash ^= $property_name$.GetHashCode();\n" - "}\n"); + "if ($has_property_check$) hash ^= $property_name$.GetHashCode();\n"); } void PrimitiveFieldGenerator::WriteEquals(io::Printer* printer) { printer->Print( @@ -147,17 +145,17 @@ void PrimitiveOneofFieldGenerator::GenerateMembers(io::Printer* printer) { variables_, "public $type_name$ $property_name$ {\n" " get { return $has_property_check$ ? ($type_name$) $oneof_name$_ : $default_value$; }\n" - " set {"); + " set {\n"); if (is_value_type) { printer->Print( variables_, - " $oneof_name$_ = value;\n" - " $oneof_name$Case_ = $oneof_property_name$Case.$property_name$;\n"); + " $oneof_name$_ = value;\n" + " $oneof_name$Case_ = $oneof_property_name$OneofCase.$property_name$;\n"); } else { printer->Print( variables_, - " $oneof_name$_ = value ?? $default_value$;\n" - " $oneof_name$Case_ = value == null ? $oneof_property_name$Case.None : $oneof_property_name$Case.$property_name$;\n"); + " $oneof_name$_ = value ?? $default_value$;\n" + " $oneof_name$Case_ = value == null ? $oneof_property_name$OneofCase.None : $oneof_property_name$OneofCase.$property_name$;\n"); } printer->Print( " }\n" diff --git a/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc b/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc index f5d5a126..ebbbf3be 100644 --- a/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc @@ -49,6 +49,7 @@ namespace csharp { RepeatedEnumFieldGenerator::RepeatedEnumFieldGenerator( const FieldDescriptor* descriptor, int fieldOrdinal) : FieldGeneratorBase(descriptor, fieldOrdinal) { + variables_["packed"] = descriptor->is_packed() ? "Packed" : ""; } RepeatedEnumFieldGenerator::~RepeatedEnumFieldGenerator() { @@ -75,27 +76,21 @@ void RepeatedEnumFieldGenerator::GenerateMergingCode(io::Printer* printer) { void RepeatedEnumFieldGenerator::GenerateParsingCode(io::Printer* printer) { printer->Print( variables_, - "input.ReadEnumArray<$type_name$>(tag, fieldName, result.$name$_);\n"); + "input.ReadEnumArray<$type_name$>(tag, fieldName, $name$_);\n"); } void RepeatedEnumFieldGenerator::GenerateSerializationCode(io::Printer* printer) { // TODO(jonskeet): Originally, this checked for Count > 0 first. // The Write* call should make that cheap though - no need to generate it every time. - if (descriptor_->is_packed()) { - printer->Print( - variables_, - "output.WritePackedEnumArray($number$, fieldNames[$field_ordinal$], $name$_);\n"); - } else { - printer->Print(variables_, - "output.WriteEnumArray($number$, fieldNames[$field_ordinal$], $name$_);\n"); - } - printer->Print("}\n"); + printer->Print( + variables_, + "output.Write$packed$EnumArray($number$, fieldNames[$field_ordinal$], $name$_);\n"); } void RepeatedEnumFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { + // TODO(jonskeet): Move all this code into CodedOutputStream? It's a lot to repeat everywhere... printer->Print("{\n"); printer->Indent(); - // TODO(jonskeet): Move all this code into CodedOutputStream? It's a lot to repeat everywhere... printer->Print( variables_, "int dataSize = 0;\n" @@ -104,7 +99,7 @@ void RepeatedEnumFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer printer->Print( variables_, "foreach ($type_name$ element in $name$_) {\n" - " dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag((long) element);\n" + " dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag(element);\n" "}\n" "size += dataSize;\n"); int tagSize = internal::WireFormat::TagSize(descriptor_->number(), descriptor_->type()); @@ -127,15 +122,13 @@ void RepeatedEnumFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer void RepeatedEnumFieldGenerator::WriteHash(io::Printer* printer) { printer->Print( variables_, - "foreach($type_name$ i in $name$_) {\n" - " hash ^= i.GetHashCode();\n" - "}\n"); + "hash ^= $name$_.GetHashCode();\n"); } void RepeatedEnumFieldGenerator::WriteEquals(io::Printer* printer) { printer->Print( variables_, - "if(!$name$_.Equals(other.$name$)) return false;\n"); + "if(!$name$_.Equals(other.$name$_)) return false;\n"); } void RepeatedEnumFieldGenerator::WriteToString(io::Printer* printer) { diff --git a/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc b/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc index 2a6a01f5..963f841e 100644 --- a/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc @@ -64,21 +64,6 @@ void RepeatedMessageFieldGenerator::GenerateMembers(io::Printer* printer) { "public pbc::RepeatedField<$type_name$> $property_name$ {\n" " get { return $name$_; }\n" "}\n"); - - // TODO(jonskeet): Redundant API calls? Possibly - include for portability though. Maybe create an option. - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public int $property_name$Count {\n" - " get { return $name$_.Count; }\n" - "}\n"); - - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public $type_name$ Get$property_name$(int index) {\n" - " return $name$_[index];\n" - "}\n"); } void RepeatedMessageFieldGenerator::GenerateMergingCode(io::Printer* printer) { @@ -90,7 +75,7 @@ void RepeatedMessageFieldGenerator::GenerateMergingCode(io::Printer* printer) { void RepeatedMessageFieldGenerator::GenerateParsingCode(io::Printer* printer) { printer->Print( variables_, - "input.ReadMessageArray(tag, fieldName, $name$_);\n"); + "input.ReadMessageArray(tag, fieldName, $name$_, $type_name$.Parser);\n"); } void RepeatedMessageFieldGenerator::GenerateSerializationCode(io::Printer* printer) { @@ -105,7 +90,7 @@ void RepeatedMessageFieldGenerator::GenerateSerializedSizeCode(io::Printer* prin // TODO(jonskeet): Put this into CodedOutputStream. printer->Print( variables_, - "foreach ($type_name$ element in $property_name$) {\n" + "foreach ($type_name$ element in $name$_) {\n" " size += pb::CodedOutputStream.ComputeMessageSize($number$, element);\n" "}\n"); } @@ -113,15 +98,15 @@ void RepeatedMessageFieldGenerator::GenerateSerializedSizeCode(io::Printer* prin void RepeatedMessageFieldGenerator::WriteHash(io::Printer* printer) { printer->Print( variables_, - "foreach($type_name$ i in $name$_) {\n" - " hash ^= i.GetHashCode();\n" - "}\n"); + "hash ^= $name$_.GetHashCode();\n"); } + void RepeatedMessageFieldGenerator::WriteEquals(io::Printer* printer) { printer->Print( variables_, - "if(!$name$_.Equals(other.$name$)) return false;\n"); + "if(!$name$_.Equals(other.$name$_)) return false;\n"); } + void RepeatedMessageFieldGenerator::WriteToString(io::Printer* printer) { variables_["field_name"] = GetFieldName(descriptor_); printer->Print( diff --git a/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc b/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc index 2001b849..0a91c3c6 100644 --- a/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc @@ -92,7 +92,7 @@ void RepeatedPrimitiveFieldGenerator::GenerateSerializationCode( void RepeatedPrimitiveFieldGenerator::GenerateSerializedSizeCode( io::Printer* printer) { - // TODO(jonskeet): Get rid of most of this - move it into the runtime. + // TODO(jonskeet): Do this in the runtime if possible. It's a pain, but it must be feasible... printer->Print("{\n"); printer->Indent(); printer->Print("int dataSize = 0;\n"); @@ -100,7 +100,7 @@ void RepeatedPrimitiveFieldGenerator::GenerateSerializedSizeCode( if (fixedSize == -1) { printer->Print( variables_, - "foreach ($type_name$ element in $property_name$List) {\n" + "foreach ($type_name$ element in $name$_) {\n" " dataSize += pb::CodedOutputStream.Compute$capitalized_type_name$SizeNoTag(element);\n" "}\n"); } else { @@ -128,14 +128,12 @@ void RepeatedPrimitiveFieldGenerator::GenerateSerializedSizeCode( void RepeatedPrimitiveFieldGenerator::WriteHash(io::Printer* printer) { printer->Print( variables_, - "foreach($type_name$ i in $name$_)\n {" - " hash ^= i.GetHashCode();\n" - "}\n"); + "hash ^= $name$_.GetHashCode();\n"); } void RepeatedPrimitiveFieldGenerator::WriteEquals(io::Printer* printer) { printer->Print( variables_, - "if(!$name$_.Equals(other.$name$)) return false;\n"); + "if(!$name$_.Equals(other.$name$_)) return false;\n"); } void RepeatedPrimitiveFieldGenerator::WriteToString(io::Printer* printer) { printer->Print(variables_, diff --git a/src/google/protobuf/descriptor.proto b/src/google/protobuf/descriptor.proto index 20a60080..97741b6a 100644 --- a/src/google/protobuf/descriptor.proto +++ b/src/google/protobuf/descriptor.proto @@ -42,7 +42,7 @@ syntax = "proto2"; package google.protobuf; option java_package = "com.google.protobuf"; option java_outer_classname = "DescriptorProtos"; -option csharp_namespace = "Google.ProtocolBuffers.DescriptorProtos"; +option csharp_namespace = "Google.Protobuf.DescriptorProtos"; option objc_class_prefix = "GPB"; // descriptor.proto must be optimized for speed because reflection-based diff --git a/src/google/protobuf/unittest_import_proto3.proto b/src/google/protobuf/unittest_import_proto3.proto new file mode 100644 index 00000000..59673eaf --- /dev/null +++ b/src/google/protobuf/unittest_import_proto3.proto @@ -0,0 +1,68 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// 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. +// +// A proto file which is imported by unittest_proto3.proto to test importing. + +syntax = "proto3"; + +// We don't put this in a package within proto2 because we need to make sure +// that the generated code doesn't depend on being in the proto2 namespace. +// In test_util.h we do +// "using namespace unittest_import = protobuf_unittest_import". +package protobuf_unittest_import; + +option optimize_for = SPEED; +option cc_enable_arenas = true; + +// Exercise the java_package option. +option java_package = "com.google.protobuf.test"; +option csharp_namespace = "Google.Protobuf.TestProtos"; + +// Do not set a java_outer_classname here to verify that Proto2 works without +// one. + +// Test public import +import public "google/protobuf/unittest_import_public_proto3.proto"; + +message ImportMessage { + int32 d = 1; +} + +enum ImportEnum { + IMPORT_ENUM_UNSPECIFIED = 0; + IMPORT_FOO = 7; + IMPORT_BAR = 8; + IMPORT_BAZ = 9; +} + diff --git a/src/google/protobuf/unittest_import_public_proto3.proto b/src/google/protobuf/unittest_import_public_proto3.proto new file mode 100644 index 00000000..d6f11e28 --- /dev/null +++ b/src/google/protobuf/unittest_import_public_proto3.proto @@ -0,0 +1,42 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// 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: liujisi@google.com (Pherl Liu) + +syntax = "proto3"; + +package protobuf_unittest_import; + +option java_package = "com.google.protobuf.test"; +option csharp_namespace = "Google.Protobuf.TestProtos"; + +message PublicImportMessage { + int32 e = 1; +} diff --git a/src/google/protobuf/unittest_proto3.proto b/src/google/protobuf/unittest_proto3.proto new file mode 100644 index 00000000..f59d2178 --- /dev/null +++ b/src/google/protobuf/unittest_proto3.proto @@ -0,0 +1,388 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// 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. +// +// A proto file we will use for unit testing. + +syntax = "proto3"; + +// Some generic_services option(s) added automatically. +// See: http://go/proto2-generic-services-default +option cc_generic_services = true; // auto-added +option java_generic_services = true; // auto-added +option py_generic_services = true; // auto-added +option cc_enable_arenas = true; +option csharp_namespace = "Google.Protobuf.TestProtos"; + +import "google/protobuf/unittest_import_proto3.proto"; + +// We don't put this in a package within proto2 because we need to make sure +// that the generated code doesn't depend on being in the proto2 namespace. +// In test_util.h we do "using namespace unittest = protobuf_unittest". +package protobuf_unittest; + +// Protos optimized for SPEED use a strict superset of the generated code +// of equivalent ones optimized for CODE_SIZE, so we should optimize all our +// tests for speed unless explicitly testing code size optimization. +option optimize_for = SPEED; + +option java_outer_classname = "UnittestProto"; + +// This proto includes every type of field in both singular and repeated +// forms. +message TestAllTypes { + message NestedMessage { + // The field name "b" fails to compile in proto1 because it conflicts with + // a local variable named "b" in one of the generated methods. Doh. + // This file needs to compile in proto1 to test backwards-compatibility. + int32 bb = 1; + } + + enum NestedEnum { + NESTED_ENUM_UNSPECIFIED = 0; + FOO = 1; + BAR = 2; + BAZ = 3; + NEG = -1; // Intentionally negative. + } + + // Singular + int32 single_int32 = 1; + int64 single_int64 = 2; + uint32 single_uint32 = 3; + uint64 single_uint64 = 4; + sint32 single_sint32 = 5; + sint64 single_sint64 = 6; + fixed32 single_fixed32 = 7; + fixed64 single_fixed64 = 8; + sfixed32 single_sfixed32 = 9; + sfixed64 single_sfixed64 = 10; + float single_float = 11; + double single_double = 12; + bool single_bool = 13; + string single_string = 14; + bytes single_bytes = 15; + + NestedMessage single_nested_message = 18; + ForeignMessage single_foreign_message = 19; + protobuf_unittest_import.ImportMessage single_import_message = 20; + + NestedEnum single_nested_enum = 21; + ForeignEnum single_foreign_enum = 22; + protobuf_unittest_import.ImportEnum single_import_enum = 23; + + // Defined in unittest_import_public.proto + protobuf_unittest_import.PublicImportMessage + single_public_import_message = 26; + + // Repeated + repeated int32 repeated_int32 = 31; + repeated int64 repeated_int64 = 32; + repeated uint32 repeated_uint32 = 33; + repeated uint64 repeated_uint64 = 34; + repeated sint32 repeated_sint32 = 35; + repeated sint64 repeated_sint64 = 36; + repeated fixed32 repeated_fixed32 = 37; + repeated fixed64 repeated_fixed64 = 38; + repeated sfixed32 repeated_sfixed32 = 39; + repeated sfixed64 repeated_sfixed64 = 40; + repeated float repeated_float = 41; + repeated double repeated_double = 42; + repeated bool repeated_bool = 43; + repeated string repeated_string = 44; + repeated bytes repeated_bytes = 45; + + repeated NestedMessage repeated_nested_message = 48; + repeated ForeignMessage repeated_foreign_message = 49; + repeated protobuf_unittest_import.ImportMessage repeated_import_message = 50; + + repeated NestedEnum repeated_nested_enum = 51; + repeated ForeignEnum repeated_foreign_enum = 52; + repeated protobuf_unittest_import.ImportEnum repeated_import_enum = 53; + // Defined in unittest_import_public.proto + repeated protobuf_unittest_import.PublicImportMessage + repeated_public_import_message = 54; + + // For oneof test + oneof oneof_field { + uint32 oneof_uint32 = 111; + NestedMessage oneof_nested_message = 112; + string oneof_string = 113; + bytes oneof_bytes = 114; + } +} + +// This proto includes a recusively nested message. +message NestedTestAllTypes { + NestedTestAllTypes child = 1; + TestAllTypes payload = 2; + repeated NestedTestAllTypes repeated_child = 3; +} + +message TestDeprecatedFields { + int32 deprecated_int32 = 1 [deprecated=true]; +} + +// Define these after TestAllTypes to make sure the compiler can handle +// that. +message ForeignMessage { + int32 c = 1; +} + +enum ForeignEnum { + FOREIGN_UNSPECIFIED = 0; + FOREIGN_FOO = 4; + FOREIGN_BAR = 5; + FOREIGN_BAZ = 6; +} + +message TestReservedFields { + reserved 2, 15, 9 to 11; + reserved "bar", "baz"; +} + + +// Test that we can use NestedMessage from outside TestAllTypes. +message TestForeignNested { + TestAllTypes.NestedMessage foreign_nested = 1; +} + +// Test that really large tag numbers don't break anything. +message TestReallyLargeTagNumber { + // The largest possible tag number is 2^28 - 1, since the wire format uses + // three bits to communicate wire type. + int32 a = 1; + int32 bb = 268435455; +} + +message TestRecursiveMessage { + TestRecursiveMessage a = 1; + int32 i = 2; +} + +// Test that mutual recursion works. +message TestMutualRecursionA { + TestMutualRecursionB bb = 1; +} + +message TestMutualRecursionB { + TestMutualRecursionA a = 1; + int32 optional_int32 = 2; +} + + +// Test an enum that has multiple values with the same number. +enum TestEnumWithDupValue { + TEST_ENUM_WITH_DUP_VALUE_UNSPECIFIED = 0; + option allow_alias = true; + + FOO1 = 1; + BAR1 = 2; + BAZ = 3; + FOO2 = 1; + BAR2 = 2; +} + +// Test an enum with large, unordered values. +enum TestSparseEnum { + TEST_SPARSE_ENUM_UNSPECIFIED = 0; + SPARSE_A = 123; + SPARSE_B = 62374; + SPARSE_C = 12589234; + SPARSE_D = -15; + SPARSE_E = -53452; + // In proto3, value 0 must be the first one specified + // SPARSE_F = 0; + SPARSE_G = 2; +} + +// Test message with CamelCase field names. This violates Protocol Buffer +// standard style. +message TestCamelCaseFieldNames { + int32 PrimitiveField = 1; + string StringField = 2; + ForeignEnum EnumField = 3; + ForeignMessage MessageField = 4; + + repeated int32 RepeatedPrimitiveField = 7; + repeated string RepeatedStringField = 8; + repeated ForeignEnum RepeatedEnumField = 9; + repeated ForeignMessage RepeatedMessageField = 10; +} + + +// We list fields out of order, to ensure that we're using field number and not +// field index to determine serialization order. +message TestFieldOrderings { + string my_string = 11; + int64 my_int = 1; + float my_float = 101; + message NestedMessage { + int64 oo = 2; + // The field name "b" fails to compile in proto1 because it conflicts with + // a local variable named "b" in one of the generated methods. Doh. + // This file needs to compile in proto1 to test backwards-compatibility. + int32 bb = 1; + } + + NestedMessage single_nested_message = 200; +} + +message SparseEnumMessage { + TestSparseEnum sparse_enum = 1; +} + +// Test String and Bytes: string is for valid UTF-8 strings +message OneString { + string data = 1; +} + +message MoreString { + repeated string data = 1; +} + +message OneBytes { + bytes data = 1; +} + +message MoreBytes { + bytes data = 1; +} + +// Test int32, uint32, int64, uint64, and bool are all compatible +message Int32Message { + int32 data = 1; +} + +message Uint32Message { + uint32 data = 1; +} + +message Int64Message { + int64 data = 1; +} + +message Uint64Message { + uint64 data = 1; +} + +message BoolMessage { + bool data = 1; +} + +// Test oneofs. +message TestOneof { + oneof foo { + int32 foo_int = 1; + string foo_string = 2; + TestAllTypes foo_message = 3; + } +} + +// Test messages for packed fields + +message TestPackedTypes { + repeated int32 packed_int32 = 90 [packed = true]; + repeated int64 packed_int64 = 91 [packed = true]; + repeated uint32 packed_uint32 = 92 [packed = true]; + repeated uint64 packed_uint64 = 93 [packed = true]; + repeated sint32 packed_sint32 = 94 [packed = true]; + repeated sint64 packed_sint64 = 95 [packed = true]; + repeated fixed32 packed_fixed32 = 96 [packed = true]; + repeated fixed64 packed_fixed64 = 97 [packed = true]; + repeated sfixed32 packed_sfixed32 = 98 [packed = true]; + repeated sfixed64 packed_sfixed64 = 99 [packed = true]; + repeated float packed_float = 100 [packed = true]; + repeated double packed_double = 101 [packed = true]; + repeated bool packed_bool = 102 [packed = true]; + repeated 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 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; +} + +message TestCommentInjectionMessage { + // */ <- This should not close the generated doc comment + string a = 1; +} + + +// Test that RPC services work. +message FooRequest {} +message FooResponse {} + +message FooClientMessage {} +message FooServerMessage{} + +service TestService { + rpc Foo(FooRequest) returns (FooResponse); + rpc Bar(BarRequest) returns (BarResponse); +} + + +message BarRequest {} +message BarResponse {} + -- cgit v1.2.3 From 39aaf21d5194fdc07c296847def8e7795279e041 Mon Sep 17 00:00:00 2001 From: Jon Skeet Date: Thu, 11 Jun 2015 21:15:36 +0100 Subject: Reimplement enums as int values, and get rid of EnumHelper. This makes repeated fields really awkward at the moment - but when we reimplement RepeatedField to be backed by an array, we can cast the array directly... --- .../ProtocolBuffers.Test/CodedInputStreamTest.cs | 6 +- .../ProtocolBuffers.Test/CodedOutputStreamTest.cs | 10 +-- .../TestProtos/UnittestImportProto3.cs | 2 +- .../TestProtos/UnittestIssues.cs | 28 ++++--- .../TestProtos/UnittestProto3.cs | 65 ++++++++------- csharp/src/ProtocolBuffers/CodedInputStream.cs | 17 ++-- .../CodedOutputStream.ComputeSize.cs | 12 +-- csharp/src/ProtocolBuffers/CodedOutputStream.cs | 24 ++++-- .../DescriptorProtos/DescriptorProtoFile.cs | 55 +++++++------ csharp/src/ProtocolBuffers/EnumHelper.cs | 93 ---------------------- csharp/src/ProtocolBuffers/ICodedInputStream.cs | 11 +-- csharp/src/ProtocolBuffers/ICodedOutputStream.cs | 2 +- csharp/src/ProtocolBuffers/ProtocolBuffers.csproj | 1 - src/google/protobuf/compiler/csharp/csharp_enum.cc | 2 +- .../protobuf/compiler/csharp/csharp_enum_field.cc | 15 ++-- .../compiler/csharp/csharp_repeated_enum_field.cc | 2 +- 16 files changed, 137 insertions(+), 208 deletions(-) delete mode 100644 csharp/src/ProtocolBuffers/EnumHelper.cs (limited to 'src/google') diff --git a/csharp/src/ProtocolBuffers.Test/CodedInputStreamTest.cs b/csharp/src/ProtocolBuffers.Test/CodedInputStreamTest.cs index 57650049..aa2da330 100644 --- a/csharp/src/ProtocolBuffers.Test/CodedInputStreamTest.cs +++ b/csharp/src/ProtocolBuffers.Test/CodedInputStreamTest.cs @@ -466,18 +466,18 @@ namespace Google.Protobuf } } - enum TestNegEnum : long { None = 0, Value = -2 } + enum TestNegEnum { None = 0, Value = -2 } [Test] public void TestNegativeEnum() { byte[] bytes = new byte[10] { 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01 }; CodedInputStream input = CodedInputStream.CreateInstance(bytes); - TestNegEnum val = TestNegEnum.None; + int val = 0; Assert.IsTrue(input.ReadEnum(ref val)); Assert.IsTrue(input.IsAtEnd); - Assert.AreEqual(TestNegEnum.Value, val); + Assert.AreEqual((int) TestNegEnum.Value, val); } [Test] diff --git a/csharp/src/ProtocolBuffers.Test/CodedOutputStreamTest.cs b/csharp/src/ProtocolBuffers.Test/CodedOutputStreamTest.cs index df80b3af..fcbb7f8d 100644 --- a/csharp/src/ProtocolBuffers.Test/CodedOutputStreamTest.cs +++ b/csharp/src/ProtocolBuffers.Test/CodedOutputStreamTest.cs @@ -296,27 +296,27 @@ namespace Google.Protobuf public void TestNegativeEnumNoTag() { Assert.AreEqual(10, CodedOutputStream.ComputeInt32SizeNoTag(-2)); - Assert.AreEqual(10, CodedOutputStream.ComputeEnumSizeNoTag(TestNegEnum.Value)); + Assert.AreEqual(10, CodedOutputStream.ComputeEnumSizeNoTag((int) TestNegEnum.Value)); byte[] bytes = new byte[10]; CodedOutputStream output = CodedOutputStream.CreateInstance(bytes); - output.WriteEnumNoTag(TestNegEnum.Value); + output.WriteEnumNoTag((int) TestNegEnum.Value); Assert.AreEqual(0, output.SpaceLeft); Assert.AreEqual("FE-FF-FF-FF-FF-FF-FF-FF-FF-01", BitConverter.ToString(bytes)); } - enum TestNegEnum : long { None = 0, Value = -2 } + enum TestNegEnum { None = 0, Value = -2 } [Test] public void TestNegativeEnumWithTag() { Assert.AreEqual(11, CodedOutputStream.ComputeInt32Size(8, -2)); - Assert.AreEqual(11, CodedOutputStream.ComputeEnumSize(8, TestNegEnum.Value)); + Assert.AreEqual(11, CodedOutputStream.ComputeEnumSize(8, (int) TestNegEnum.Value)); byte[] bytes = new byte[11]; CodedOutputStream output = CodedOutputStream.CreateInstance(bytes); - output.WriteEnum(8, "", TestNegEnum.Value); + output.WriteEnum(8, "", (int) TestNegEnum.Value); Assert.AreEqual(0, output.SpaceLeft); //fyi, 0x40 == 0x08 << 3 + 0, field num + wire format shift diff --git a/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImportProto3.cs b/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImportProto3.cs index 1eb87f05..4b62794a 100644 --- a/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImportProto3.cs +++ b/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImportProto3.cs @@ -49,7 +49,7 @@ namespace Google.Protobuf.TestProtos { } #region Enums - public enum ImportEnum : long { + public enum ImportEnum { IMPORT_ENUM_UNSPECIFIED = 0, IMPORT_FOO = 7, IMPORT_BAR = 8, diff --git a/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestIssues.cs b/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestIssues.cs index fc696cf0..14ca78a4 100644 --- a/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestIssues.cs +++ b/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestIssues.cs @@ -75,13 +75,13 @@ namespace UnitTest.Issues.TestProtos { } #region Enums - public enum NegativeEnum : long { + public enum NegativeEnum { NEGATIVE_ENUM_ZERO = 0, FiveBelow = -5, MinusOne = -1, } - public enum DeprecatedEnum : long { + public enum DeprecatedEnum { DEPRECATED_ZERO = 0, one = 1, } @@ -156,7 +156,7 @@ namespace UnitTest.Issues.TestProtos { public void WriteTo(pb::ICodedOutputStream output) { string[] fieldNames = _fieldNames; if (Value != global::UnitTest.Issues.TestProtos.NegativeEnum.NEGATIVE_ENUM_ZERO) { - output.WriteEnum(1, fieldNames[1], Value); + output.WriteEnum(1, fieldNames[1], (int) Value); } output.WriteEnumArray(2, fieldNames[2], values_); output.WritePackedEnumArray(3, fieldNames[0], packedValues_); @@ -165,13 +165,13 @@ namespace UnitTest.Issues.TestProtos { public int CalculateSize() { int size = 0; if (Value != global::UnitTest.Issues.TestProtos.NegativeEnum.NEGATIVE_ENUM_ZERO) { - size += pb::CodedOutputStream.ComputeEnumSize(1, Value); + size += pb::CodedOutputStream.ComputeEnumSize(1, (int) Value); } { int dataSize = 0; if (values_.Count > 0) { foreach (global::UnitTest.Issues.TestProtos.NegativeEnum element in values_) { - dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag((int) element); } size += dataSize; size += 1 * values_.Count; @@ -181,7 +181,7 @@ namespace UnitTest.Issues.TestProtos { int dataSize = 0; if (packedValues_.Count > 0) { foreach (global::UnitTest.Issues.TestProtos.NegativeEnum element in packedValues_) { - dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag((int) element); } size += dataSize; size += 1; @@ -220,8 +220,9 @@ namespace UnitTest.Issues.TestProtos { } break; case 8: { - input.ReadEnum(ref value_); - break; + int tmp = 0; + input.ReadEnum(ref tmp); + value_ = (global::UnitTest.Issues.TestProtos.NegativeEnum) tmp;break; } case 18: case 16: { @@ -422,7 +423,7 @@ namespace UnitTest.Issues.TestProtos { } output.WriteMessageArray(4, fieldNames[2], messageArray_); if (EnumValue != global::UnitTest.Issues.TestProtos.DeprecatedEnum.DEPRECATED_ZERO) { - output.WriteEnum(5, fieldNames[1], EnumValue); + output.WriteEnum(5, fieldNames[1], (int) EnumValue); } output.WritePackedEnumArray(6, fieldNames[0], enumArray_); } @@ -449,13 +450,13 @@ namespace UnitTest.Issues.TestProtos { size += pb::CodedOutputStream.ComputeMessageSize(4, element); } if (EnumValue != global::UnitTest.Issues.TestProtos.DeprecatedEnum.DEPRECATED_ZERO) { - size += pb::CodedOutputStream.ComputeEnumSize(5, EnumValue); + size += pb::CodedOutputStream.ComputeEnumSize(5, (int) EnumValue); } { int dataSize = 0; if (enumArray_.Count > 0) { foreach (global::UnitTest.Issues.TestProtos.DeprecatedEnum element in enumArray_) { - dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag((int) element); } size += dataSize; size += 1; @@ -524,8 +525,9 @@ namespace UnitTest.Issues.TestProtos { break; } case 40: { - input.ReadEnum(ref enumValue_); - break; + int tmp = 0; + input.ReadEnum(ref tmp); + enumValue_ = (global::UnitTest.Issues.TestProtos.DeprecatedEnum) tmp;break; } case 50: case 48: { diff --git a/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestProto3.cs b/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestProto3.cs index e231bb95..3e5bb8b6 100644 --- a/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestProto3.cs +++ b/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestProto3.cs @@ -372,14 +372,14 @@ namespace Google.Protobuf.TestProtos { } #region Enums - public enum ForeignEnum : long { + public enum ForeignEnum { FOREIGN_UNSPECIFIED = 0, FOREIGN_FOO = 4, FOREIGN_BAR = 5, FOREIGN_BAZ = 6, } - public enum TestEnumWithDupValue : long { + public enum TestEnumWithDupValue { TEST_ENUM_WITH_DUP_VALUE_UNSPECIFIED = 0, FOO1 = 1, BAR1 = 2, @@ -388,7 +388,7 @@ namespace Google.Protobuf.TestProtos { BAR2 = 2, } - public enum TestSparseEnum : long { + public enum TestSparseEnum { TEST_SPARSE_ENUM_UNSPECIFIED = 0, SPARSE_A = 123, SPARSE_B = 62374, @@ -945,13 +945,13 @@ namespace Google.Protobuf.TestProtos { output.WriteMessage(20, fieldNames[35], SingleImportMessage); } if (SingleNestedEnum != global::Google.Protobuf.TestProtos.TestAllTypes.Types.NestedEnum.NESTED_ENUM_UNSPECIFIED) { - output.WriteEnum(21, fieldNames[38], SingleNestedEnum); + output.WriteEnum(21, fieldNames[38], (int) SingleNestedEnum); } if (SingleForeignEnum != global::Google.Protobuf.TestProtos.ForeignEnum.FOREIGN_UNSPECIFIED) { - output.WriteEnum(22, fieldNames[32], SingleForeignEnum); + output.WriteEnum(22, fieldNames[32], (int) SingleForeignEnum); } if (SingleImportEnum != global::Google.Protobuf.TestProtos.ImportEnum.IMPORT_ENUM_UNSPECIFIED) { - output.WriteEnum(23, fieldNames[34], SingleImportEnum); + output.WriteEnum(23, fieldNames[34], (int) SingleImportEnum); } if (singlePublicImportMessage_ != null) { output.WriteMessage(26, fieldNames[40], SinglePublicImportMessage); @@ -1049,13 +1049,13 @@ namespace Google.Protobuf.TestProtos { size += pb::CodedOutputStream.ComputeMessageSize(20, SingleImportMessage); } if (SingleNestedEnum != global::Google.Protobuf.TestProtos.TestAllTypes.Types.NestedEnum.NESTED_ENUM_UNSPECIFIED) { - size += pb::CodedOutputStream.ComputeEnumSize(21, SingleNestedEnum); + size += pb::CodedOutputStream.ComputeEnumSize(21, (int) SingleNestedEnum); } if (SingleForeignEnum != global::Google.Protobuf.TestProtos.ForeignEnum.FOREIGN_UNSPECIFIED) { - size += pb::CodedOutputStream.ComputeEnumSize(22, SingleForeignEnum); + size += pb::CodedOutputStream.ComputeEnumSize(22, (int) SingleForeignEnum); } if (SingleImportEnum != global::Google.Protobuf.TestProtos.ImportEnum.IMPORT_ENUM_UNSPECIFIED) { - size += pb::CodedOutputStream.ComputeEnumSize(23, SingleImportEnum); + size += pb::CodedOutputStream.ComputeEnumSize(23, (int) SingleImportEnum); } if (singlePublicImportMessage_ != null) { size += pb::CodedOutputStream.ComputeMessageSize(26, SinglePublicImportMessage); @@ -1205,7 +1205,7 @@ namespace Google.Protobuf.TestProtos { int dataSize = 0; if (repeatedNestedEnum_.Count > 0) { foreach (global::Google.Protobuf.TestProtos.TestAllTypes.Types.NestedEnum element in repeatedNestedEnum_) { - dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag((int) element); } size += dataSize; size += 2; @@ -1216,7 +1216,7 @@ namespace Google.Protobuf.TestProtos { int dataSize = 0; if (repeatedForeignEnum_.Count > 0) { foreach (global::Google.Protobuf.TestProtos.ForeignEnum element in repeatedForeignEnum_) { - dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag((int) element); } size += dataSize; size += 2; @@ -1227,7 +1227,7 @@ namespace Google.Protobuf.TestProtos { int dataSize = 0; if (repeatedImportEnum_.Count > 0) { foreach (global::Google.Protobuf.TestProtos.ImportEnum element in repeatedImportEnum_) { - dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag((int) element); } size += dataSize; size += 2; @@ -1472,16 +1472,19 @@ namespace Google.Protobuf.TestProtos { break; } case 168: { - input.ReadEnum(ref singleNestedEnum_); - break; + int tmp = 0; + input.ReadEnum(ref tmp); + singleNestedEnum_ = (global::Google.Protobuf.TestProtos.TestAllTypes.Types.NestedEnum) tmp;break; } case 176: { - input.ReadEnum(ref singleForeignEnum_); - break; + int tmp = 0; + input.ReadEnum(ref tmp); + singleForeignEnum_ = (global::Google.Protobuf.TestProtos.ForeignEnum) tmp;break; } case 184: { - input.ReadEnum(ref singleImportEnum_); - break; + int tmp = 0; + input.ReadEnum(ref tmp); + singleImportEnum_ = (global::Google.Protobuf.TestProtos.ImportEnum) tmp;break; } case 210: { if (singlePublicImportMessage_ == null) { @@ -1634,7 +1637,7 @@ namespace Google.Protobuf.TestProtos { #region Nested types [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class Types { - public enum NestedEnum : long { + public enum NestedEnum { NESTED_ENUM_UNSPECIFIED = 0, FOO = 1, BAR = 2, @@ -2865,7 +2868,7 @@ namespace Google.Protobuf.TestProtos { output.WriteString(2, fieldNames[7], StringField); } if (EnumField != global::Google.Protobuf.TestProtos.ForeignEnum.FOREIGN_UNSPECIFIED) { - output.WriteEnum(3, fieldNames[0], EnumField); + output.WriteEnum(3, fieldNames[0], (int) EnumField); } if (messageField_ != null) { output.WriteMessage(4, fieldNames[1], MessageField); @@ -2885,7 +2888,7 @@ namespace Google.Protobuf.TestProtos { size += pb::CodedOutputStream.ComputeStringSize(2, StringField); } if (EnumField != global::Google.Protobuf.TestProtos.ForeignEnum.FOREIGN_UNSPECIFIED) { - size += pb::CodedOutputStream.ComputeEnumSize(3, EnumField); + size += pb::CodedOutputStream.ComputeEnumSize(3, (int) EnumField); } if (messageField_ != null) { size += pb::CodedOutputStream.ComputeMessageSize(4, MessageField); @@ -2912,7 +2915,7 @@ namespace Google.Protobuf.TestProtos { int dataSize = 0; if (repeatedEnumField_.Count > 0) { foreach (global::Google.Protobuf.TestProtos.ForeignEnum element in repeatedEnumField_) { - dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag((int) element); } size += dataSize; size += 1; @@ -2976,8 +2979,9 @@ namespace Google.Protobuf.TestProtos { break; } case 24: { - input.ReadEnum(ref enumField_); - break; + int tmp = 0; + input.ReadEnum(ref tmp); + enumField_ = (global::Google.Protobuf.TestProtos.ForeignEnum) tmp;break; } case 34: { if (messageField_ == null) { @@ -3361,14 +3365,14 @@ namespace Google.Protobuf.TestProtos { public void WriteTo(pb::ICodedOutputStream output) { string[] fieldNames = _fieldNames; if (SparseEnum != global::Google.Protobuf.TestProtos.TestSparseEnum.TEST_SPARSE_ENUM_UNSPECIFIED) { - output.WriteEnum(1, fieldNames[0], SparseEnum); + output.WriteEnum(1, fieldNames[0], (int) SparseEnum); } } public int CalculateSize() { int size = 0; if (SparseEnum != global::Google.Protobuf.TestProtos.TestSparseEnum.TEST_SPARSE_ENUM_UNSPECIFIED) { - size += pb::CodedOutputStream.ComputeEnumSize(1, SparseEnum); + size += pb::CodedOutputStream.ComputeEnumSize(1, (int) SparseEnum); } return size; } @@ -3400,8 +3404,9 @@ namespace Google.Protobuf.TestProtos { } break; case 8: { - input.ReadEnum(ref sparseEnum_); - break; + int tmp = 0; + input.ReadEnum(ref tmp); + sparseEnum_ = (global::Google.Protobuf.TestProtos.TestSparseEnum) tmp;break; } } } @@ -4769,7 +4774,7 @@ namespace Google.Protobuf.TestProtos { int dataSize = 0; if (packedEnum_.Count > 0) { foreach (global::Google.Protobuf.TestProtos.ForeignEnum element in packedEnum_) { - dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag((int) element); } size += dataSize; size += 2; @@ -5156,7 +5161,7 @@ namespace Google.Protobuf.TestProtos { int dataSize = 0; if (unpackedEnum_.Count > 0) { foreach (global::Google.Protobuf.TestProtos.ForeignEnum element in unpackedEnum_) { - dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag((int) element); } size += dataSize; size += 2 * unpackedEnum_.Count; diff --git a/csharp/src/ProtocolBuffers/CodedInputStream.cs b/csharp/src/ProtocolBuffers/CodedInputStream.cs index 685d7702..d5cab6fd 100644 --- a/csharp/src/ProtocolBuffers/CodedInputStream.cs +++ b/csharp/src/ProtocolBuffers/CodedInputStream.cs @@ -434,11 +434,10 @@ namespace Google.Protobuf /// then the ref value is set and it returns true. Otherwise the unknown output /// value is set and this method returns false. /// - public bool ReadEnum(ref T value) - where T : struct, IComparable, IFormattable + public bool ReadEnum(ref int value) { - int number = (int) ReadRawVarint32(); - value = EnumHelper.FromInt32(number); + // Currently just a pass-through, but it's nice to separate it logically from WriteInt32. + value = (int) ReadRawVarint32(); return true; } @@ -796,7 +795,7 @@ namespace Google.Protobuf public void ReadEnumArray(uint fieldTag, string fieldName, ICollection list) where T : struct, IComparable, IFormattable { - T value = default(T); + int value = 0; WireFormat.WireType wformat = WireFormat.GetTagWireType(fieldTag); // 2.3 allows packed form even if the field is not declared packed. @@ -806,8 +805,9 @@ namespace Google.Protobuf int limit = PushLimit(length); while (!ReachedLimit) { - ReadEnum(ref value); - list.Add(value); + ReadEnum(ref value); + // TODO(jonskeet): Avoid this horrible boxing! + list.Add((T)(object)value); } PopLimit(limit); } @@ -816,7 +816,8 @@ namespace Google.Protobuf do { ReadEnum(ref value); - list.Add(value); + // TODO(jonskeet): Avoid this horrible boxing! + list.Add((T)(object) value); } while (ContinueArray(fieldTag)); } } diff --git a/csharp/src/ProtocolBuffers/CodedOutputStream.ComputeSize.cs b/csharp/src/ProtocolBuffers/CodedOutputStream.ComputeSize.cs index 58475ff7..96be9db5 100644 --- a/csharp/src/ProtocolBuffers/CodedOutputStream.ComputeSize.cs +++ b/csharp/src/ProtocolBuffers/CodedOutputStream.ComputeSize.cs @@ -196,7 +196,7 @@ namespace Google.Protobuf /// enum field, including the tag. The caller is responsible for /// converting the enum value to its numeric value. /// - public static int ComputeEnumSize(int fieldNumber, T value) where T : struct, IComparable, IFormattable + public static int ComputeEnumSize(int fieldNumber, int value) { return ComputeTagSize(fieldNumber) + ComputeEnumSizeNoTag(value); } @@ -371,10 +371,10 @@ namespace Google.Protobuf /// enum field, including the tag. The caller is responsible for /// converting the enum value to its numeric value. /// - public static int ComputeEnumSizeNoTag(T value) where T : struct, IComparable, IFormattable + public static int ComputeEnumSizeNoTag(int value) { - int serializedValue = EnumHelper.ToInt32(value); - return ComputeInt32SizeNoTag(serializedValue); + // Currently just a pass-through, but it's nice to separate it logically. + return ComputeInt32SizeNoTag(value); } /// @@ -555,7 +555,7 @@ namespace Google.Protobuf case FieldType.SInt64: return ComputeSInt64Size(fieldNumber, (long) value); case FieldType.Enum: - return ComputeEnumSize(fieldNumber, Convert.ToInt64(value)); + return ComputeEnumSize(fieldNumber, (int) value); default: throw new ArgumentOutOfRangeException("Invalid field type " + fieldType); } @@ -605,7 +605,7 @@ namespace Google.Protobuf case FieldType.SInt64: return ComputeSInt64SizeNoTag((long) value); case FieldType.Enum: - return ComputeEnumSizeNoTag(Convert.ToInt64(value)); + return ComputeEnumSizeNoTag((int) value); default: throw new ArgumentOutOfRangeException("Invalid field type " + fieldType); } diff --git a/csharp/src/ProtocolBuffers/CodedOutputStream.cs b/csharp/src/ProtocolBuffers/CodedOutputStream.cs index f55f8ca2..e3f0c700 100644 --- a/csharp/src/ProtocolBuffers/CodedOutputStream.cs +++ b/csharp/src/ProtocolBuffers/CodedOutputStream.cs @@ -37,6 +37,7 @@ using System; using System.Collections; using System.IO; +using System.Linq; using System.Text; using Google.Protobuf.Collections; using Google.Protobuf.Descriptors; @@ -350,10 +351,11 @@ namespace Google.Protobuf WriteRawVarint32(value); } - public void WriteEnum(int fieldNumber, string fieldName, T value) where T : struct, IComparable, IFormattable + public void WriteEnum(int fieldNumber, string fieldName, int value) { + // Currently just a pass-through, but it's nice to separate it logically from WriteInt32. WriteTag(fieldNumber, WireFormat.WireType.Varint); - WriteInt32NoTag(EnumHelper.ToInt32(value)); + WriteInt32NoTag(value); } public void WriteSFixed32(int fieldNumber, string fieldName, int value) @@ -595,9 +597,9 @@ namespace Google.Protobuf WriteRawVarint32(value); } - public void WriteEnumNoTag(T value) where T : struct, IComparable, IFormattable + public void WriteEnumNoTag(int value) { - WriteInt32NoTag(EnumHelper.ToInt32(value)); + WriteInt32NoTag(value); } public void WriteSFixed32NoTag(int value) @@ -774,7 +776,12 @@ namespace Google.Protobuf public void WriteEnumArray(int fieldNumber, string fieldName, RepeatedField list) where T : struct, IComparable, IFormattable { - foreach (T value in list) + if (list.Count == 0) + { + return; + } + // TODO(jonskeet): Avoid the Cast call here. Work out a better mass "T to int" conversion. + foreach (int value in list.Cast()) { WriteEnum(fieldNumber, fieldName, value); } @@ -1005,10 +1012,13 @@ namespace Google.Protobuf { return; } - uint size = list.CalculateSize(ComputeEnumSizeNoTag); + // Obviously, we'll want to get rid of this hack... + var temporaryHack = new RepeatedField(); + temporaryHack.Add(list.Cast()); + uint size = temporaryHack.CalculateSize(ComputeEnumSizeNoTag); WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited); WriteRawVarint32(size); - foreach (T value in list) + foreach (int value in temporaryHack) { WriteEnumNoTag(value); } diff --git a/csharp/src/ProtocolBuffers/DescriptorProtos/DescriptorProtoFile.cs b/csharp/src/ProtocolBuffers/DescriptorProtos/DescriptorProtoFile.cs index b18b63bf..eb96dfcf 100644 --- a/csharp/src/ProtocolBuffers/DescriptorProtos/DescriptorProtoFile.cs +++ b/csharp/src/ProtocolBuffers/DescriptorProtos/DescriptorProtoFile.cs @@ -1360,10 +1360,10 @@ namespace Google.Protobuf.DescriptorProtos { output.WriteInt32(3, fieldNames[4], Number); } if (Label != global::Google.Protobuf.DescriptorProtos.FieldDescriptorProto.Types.Label.LABEL_OPTIONAL) { - output.WriteEnum(4, fieldNames[2], Label); + output.WriteEnum(4, fieldNames[2], (int) Label); } if (Type != global::Google.Protobuf.DescriptorProtos.FieldDescriptorProto.Types.Type.TYPE_DOUBLE) { - output.WriteEnum(5, fieldNames[7], Type); + output.WriteEnum(5, fieldNames[7], (int) Type); } if (TypeName != "") { output.WriteString(6, fieldNames[8], TypeName); @@ -1388,10 +1388,10 @@ namespace Google.Protobuf.DescriptorProtos { size += pb::CodedOutputStream.ComputeInt32Size(3, Number); } if (Label != global::Google.Protobuf.DescriptorProtos.FieldDescriptorProto.Types.Label.LABEL_OPTIONAL) { - size += pb::CodedOutputStream.ComputeEnumSize(4, Label); + size += pb::CodedOutputStream.ComputeEnumSize(4, (int) Label); } if (Type != global::Google.Protobuf.DescriptorProtos.FieldDescriptorProto.Types.Type.TYPE_DOUBLE) { - size += pb::CodedOutputStream.ComputeEnumSize(5, Type); + size += pb::CodedOutputStream.ComputeEnumSize(5, (int) Type); } if (TypeName != "") { size += pb::CodedOutputStream.ComputeStringSize(6, TypeName); @@ -1477,12 +1477,14 @@ namespace Google.Protobuf.DescriptorProtos { break; } case 32: { - input.ReadEnum(ref label_); - break; + int tmp = 0; + input.ReadEnum(ref tmp); + label_ = (global::Google.Protobuf.DescriptorProtos.FieldDescriptorProto.Types.Label) tmp;break; } case 40: { - input.ReadEnum(ref type_); - break; + int tmp = 0; + input.ReadEnum(ref tmp); + type_ = (global::Google.Protobuf.DescriptorProtos.FieldDescriptorProto.Types.Type) tmp;break; } case 50: { input.ReadString(ref typeName_); @@ -1510,7 +1512,7 @@ namespace Google.Protobuf.DescriptorProtos { #region Nested types [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class Types { - public enum Type : long { + public enum Type { TYPE_DOUBLE = 1, TYPE_FLOAT = 2, TYPE_INT64 = 3, @@ -1531,7 +1533,7 @@ namespace Google.Protobuf.DescriptorProtos { TYPE_SINT64 = 18, } - public enum Label : long { + public enum Label { LABEL_OPTIONAL = 1, LABEL_REQUIRED = 2, LABEL_REPEATED = 3, @@ -2489,7 +2491,7 @@ namespace Google.Protobuf.DescriptorProtos { output.WriteString(8, fieldNames[8], JavaOuterClassname); } if (OptimizeFor != global::Google.Protobuf.DescriptorProtos.FileOptions.Types.OptimizeMode.SPEED) { - output.WriteEnum(9, fieldNames[12], OptimizeFor); + output.WriteEnum(9, fieldNames[12], (int) OptimizeFor); } if (JavaMultipleFiles != false) { output.WriteBool(10, fieldNames[7], JavaMultipleFiles); @@ -2545,7 +2547,7 @@ namespace Google.Protobuf.DescriptorProtos { size += pb::CodedOutputStream.ComputeBoolSize(27, JavaStringCheckUtf8); } if (OptimizeFor != global::Google.Protobuf.DescriptorProtos.FileOptions.Types.OptimizeMode.SPEED) { - size += pb::CodedOutputStream.ComputeEnumSize(9, OptimizeFor); + size += pb::CodedOutputStream.ComputeEnumSize(9, (int) OptimizeFor); } if (GoPackage != "") { size += pb::CodedOutputStream.ComputeStringSize(11, GoPackage); @@ -2652,8 +2654,9 @@ namespace Google.Protobuf.DescriptorProtos { break; } case 72: { - input.ReadEnum(ref optimizeFor_); - break; + int tmp = 0; + input.ReadEnum(ref tmp); + optimizeFor_ = (global::Google.Protobuf.DescriptorProtos.FileOptions.Types.OptimizeMode) tmp;break; } case 80: { input.ReadBool(ref javaMultipleFiles_); @@ -2710,7 +2713,7 @@ namespace Google.Protobuf.DescriptorProtos { #region Nested types [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class Types { - public enum OptimizeMode : long { + public enum OptimizeMode { SPEED = 1, CODE_SIZE = 2, LITE_RUNTIME = 3, @@ -3015,7 +3018,7 @@ namespace Google.Protobuf.DescriptorProtos { public void WriteTo(pb::ICodedOutputStream output) { string[] fieldNames = _fieldNames; if (Ctype != global::Google.Protobuf.DescriptorProtos.FieldOptions.Types.CType.STRING) { - output.WriteEnum(1, fieldNames[0], Ctype); + output.WriteEnum(1, fieldNames[0], (int) Ctype); } if (Packed != false) { output.WriteBool(2, fieldNames[4], Packed); @@ -3027,7 +3030,7 @@ namespace Google.Protobuf.DescriptorProtos { output.WriteBool(5, fieldNames[3], Lazy); } if (Jstype != global::Google.Protobuf.DescriptorProtos.FieldOptions.Types.JSType.JS_NORMAL) { - output.WriteEnum(6, fieldNames[2], Jstype); + output.WriteEnum(6, fieldNames[2], (int) Jstype); } if (Weak != false) { output.WriteBool(10, fieldNames[6], Weak); @@ -3038,13 +3041,13 @@ namespace Google.Protobuf.DescriptorProtos { public int CalculateSize() { int size = 0; if (Ctype != global::Google.Protobuf.DescriptorProtos.FieldOptions.Types.CType.STRING) { - size += pb::CodedOutputStream.ComputeEnumSize(1, Ctype); + size += pb::CodedOutputStream.ComputeEnumSize(1, (int) Ctype); } if (Packed != false) { size += pb::CodedOutputStream.ComputeBoolSize(2, Packed); } if (Jstype != global::Google.Protobuf.DescriptorProtos.FieldOptions.Types.JSType.JS_NORMAL) { - size += pb::CodedOutputStream.ComputeEnumSize(6, Jstype); + size += pb::CodedOutputStream.ComputeEnumSize(6, (int) Jstype); } if (Lazy != false) { size += pb::CodedOutputStream.ComputeBoolSize(5, Lazy); @@ -3104,8 +3107,9 @@ namespace Google.Protobuf.DescriptorProtos { } break; case 8: { - input.ReadEnum(ref ctype_); - break; + int tmp = 0; + input.ReadEnum(ref tmp); + ctype_ = (global::Google.Protobuf.DescriptorProtos.FieldOptions.Types.CType) tmp;break; } case 16: { input.ReadBool(ref packed_); @@ -3120,8 +3124,9 @@ namespace Google.Protobuf.DescriptorProtos { break; } case 48: { - input.ReadEnum(ref jstype_); - break; + int tmp = 0; + input.ReadEnum(ref tmp); + jstype_ = (global::Google.Protobuf.DescriptorProtos.FieldOptions.Types.JSType) tmp;break; } case 80: { input.ReadBool(ref weak_); @@ -3138,13 +3143,13 @@ namespace Google.Protobuf.DescriptorProtos { #region Nested types [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class Types { - public enum CType : long { + public enum CType { STRING = 0, CORD = 1, STRING_PIECE = 2, } - public enum JSType : long { + public enum JSType { JS_NORMAL = 0, JS_STRING = 1, JS_NUMBER = 2, diff --git a/csharp/src/ProtocolBuffers/EnumHelper.cs b/csharp/src/ProtocolBuffers/EnumHelper.cs deleted file mode 100644 index 1cf18985..00000000 --- a/csharp/src/ProtocolBuffers/EnumHelper.cs +++ /dev/null @@ -1,93 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Text; - -namespace Google.Protobuf -{ - public class EnumHelper where T : struct, IComparable, IFormattable - { - // TODO(jonskeet): For snmall enums, use something lighter-weight than a dictionary? - private static readonly Dictionary _byNumber; - private static readonly Dictionary _byName; - private static readonly Func toRawValue; - private static readonly Func fromRawValue; - - private const long UnknownValueBase = 0x100000000L; - - static EnumHelper() - { - if (!typeof(T).IsEnum) - { - throw new InvalidOperationException(string.Format("{0} is not an enum type", typeof(T).FullName)); - } - if (Enum.GetUnderlyingType(typeof(T)) != typeof(long)) - { - throw new InvalidOperationException(string.Format("{0} does not have long as an underlying type", typeof(T).FullName)); - } - // It will actually be a T[], but the CLR will let us convert. - long[] array = (long[])Enum.GetValues(typeof(T)); - _byNumber = new Dictionary(array.Length); - foreach (long i in array) - { - _byNumber[(int) i] = (T)(object)i; - } - string[] names = (string[])Enum.GetNames(typeof(T)); - _byName = new Dictionary(); - foreach (var name in names) - { - _byName[name] = (T) Enum.Parse(typeof(T), name, false); - } - - ParameterExpression param1 = Expression.Parameter(typeof(T), "x"); - ParameterExpression param2 = Expression.Parameter(typeof(long), "x"); - Expression convertedParam1 = Expression.Convert(param1, typeof(long)); - Expression convertedParam2 = Expression.Convert(param2, typeof(T)); - toRawValue = Expression.Lambda>(convertedParam1, param1).Compile(); - fromRawValue = Expression.Lambda>(convertedParam2, param2).Compile(); - } - - /// - /// Converts the given 32-bit integer into a value of the enum type. - /// If the integer is a known, named value, that is returned; otherwise, - /// a value which is outside the range of 32-bit integers but which preserves - /// the original integer is returned. - /// - public static T FromInt32(int value) - { - T validValue; - return _byNumber.TryGetValue(value, out validValue) ? validValue : FromRawValue((long) value | UnknownValueBase); - } - - /// - /// Converts a value of the enum type to a 32-bit integer. This reverses - /// . - /// - public static int ToInt32(T value) - { - return (int)GetRawValue(value); - } - - public static bool IsKnownValue(T value) - { - long raw = GetRawValue(value); - if (raw >= int.MinValue && raw <= int.MaxValue) - { - return _byNumber.ContainsKey((int)raw); - } - return false; - } - - private static long GetRawValue(T value) - { - return toRawValue(value); - } - - private static T FromRawValue(long value) - { - return fromRawValue(value); - } - - } -} diff --git a/csharp/src/ProtocolBuffers/ICodedInputStream.cs b/csharp/src/ProtocolBuffers/ICodedInputStream.cs index 748589a0..d962e62b 100644 --- a/csharp/src/ProtocolBuffers/ICodedInputStream.cs +++ b/csharp/src/ProtocolBuffers/ICodedInputStream.cs @@ -146,14 +146,11 @@ namespace Google.Protobuf bool ReadUInt32(ref uint value); /// - /// Reads an enum field value from the stream. If the enum is valid for type T, - /// then the ref value is set and it returns true. Otherwise, if a value is present - /// but invalid for the proto enum, it is still set in the field as a "preserved - /// but invalid" value, and the method returns true. If no value can be read, the - /// method does not affect the parameter and returns false. + /// Reads an enum field value from the stream. This performs no checking + /// as to whether the enum value is known to the enum type as it was present + /// when the code was generated. /// - bool ReadEnum(ref T value) - where T : struct, IComparable, IFormattable; + bool ReadEnum(ref int value); /// /// Reads an sfixed32 field value from the stream. diff --git a/csharp/src/ProtocolBuffers/ICodedOutputStream.cs b/csharp/src/ProtocolBuffers/ICodedOutputStream.cs index e51c10a4..921400ac 100644 --- a/csharp/src/ProtocolBuffers/ICodedOutputStream.cs +++ b/csharp/src/ProtocolBuffers/ICodedOutputStream.cs @@ -148,7 +148,7 @@ namespace Google.Protobuf /// /// Writes an enum field value, including tag, to the stream. /// - void WriteEnum(int fieldNumber, string fieldName, T value) where T : struct, IComparable, IFormattable; + void WriteEnum(int fieldNumber, string fieldName, int value); /// /// Writes a fixed 32-bit field value, including tag, to the stream. diff --git a/csharp/src/ProtocolBuffers/ProtocolBuffers.csproj b/csharp/src/ProtocolBuffers/ProtocolBuffers.csproj index d15f1306..efd387a2 100644 --- a/csharp/src/ProtocolBuffers/ProtocolBuffers.csproj +++ b/csharp/src/ProtocolBuffers/ProtocolBuffers.csproj @@ -84,7 +84,6 @@ - diff --git a/src/google/protobuf/compiler/csharp/csharp_enum.cc b/src/google/protobuf/compiler/csharp/csharp_enum.cc index d511bba3..0e8f9836 100644 --- a/src/google/protobuf/compiler/csharp/csharp_enum.cc +++ b/src/google/protobuf/compiler/csharp/csharp_enum.cc @@ -58,7 +58,7 @@ EnumGenerator::~EnumGenerator() { void EnumGenerator::Generate(io::Printer* printer) { WriteGeneratedCodeAttributes(printer); - printer->Print("$access_level$ enum $name$ : long {\n", + printer->Print("$access_level$ enum $name$ {\n", "access_level", class_access_level(), "name", descriptor_->name()); printer->Indent(); diff --git a/src/google/protobuf/compiler/csharp/csharp_enum_field.cc b/src/google/protobuf/compiler/csharp/csharp_enum_field.cc index ee9d6a1d..3494b228 100644 --- a/src/google/protobuf/compiler/csharp/csharp_enum_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_enum_field.cc @@ -54,14 +54,17 @@ EnumFieldGenerator::~EnumFieldGenerator() { } void EnumFieldGenerator::GenerateParsingCode(io::Printer* printer) { + // TODO(jonskeet): Get rid of the temporary variable when we sanitize CodedInputStream not to use ref. printer->Print(variables_, - "input.ReadEnum(ref $name$_);\n"); + "int tmp = 0;\n" + "input.ReadEnum(ref tmp);\n" + "$name$_ = ($type_name$) tmp;"); } void EnumFieldGenerator::GenerateSerializationCode(io::Printer* printer) { printer->Print(variables_, "if ($has_property_check$) {\n" - " output.WriteEnum($number$, fieldNames[$field_ordinal$], $property_name$);\n" + " output.WriteEnum($number$, fieldNames[$field_ordinal$], (int) $property_name$);\n" "}\n"); } @@ -69,7 +72,7 @@ void EnumFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { printer->Print( variables_, "if ($has_property_check$) {\n" - " size += pb::CodedOutputStream.ComputeEnumSize($number$, $property_name$);\n" + " size += pb::CodedOutputStream.ComputeEnumSize($number$, (int) $property_name$);\n" "}\n"); } @@ -85,7 +88,7 @@ void EnumOneofFieldGenerator::GenerateParsingCode(io::Printer* printer) { // TODO(jonskeet): What about if we read the default value? printer->Print( variables_, - "$type_name$ enumValue = $default_value$;\n" + "int enumValue = 0;\n" "if(input.ReadEnum(ref enumValue)) {\n" " $oneof_name$_ = enumValue;\n" " $oneof_name$Case_ = $oneof_property_name$OneofCase.$property_name$;\n" @@ -96,7 +99,7 @@ void EnumOneofFieldGenerator::GenerateSerializationCode(io::Printer* printer) { printer->Print( variables_, "if ($has_property_check$) {\n" - " output.WriteEnum($number$, fieldNames[$field_ordinal$], (long) $property_name$, $property_name$);\n" + " output.WriteEnum($number$, fieldNames[$field_ordinal$], (int) $property_name$);\n" "}\n"); } @@ -104,7 +107,7 @@ void EnumOneofFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { printer->Print( variables_, "if ($has_property_check$) {\n" - " size += pb::CodedOutputStream.ComputeEnumSize($number$, (long) $property_name$);\n" + " size += pb::CodedOutputStream.ComputeEnumSize($number$, (int) $property_name$);\n" "}\n"); } diff --git a/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc b/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc index ebbbf3be..937d675a 100644 --- a/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc @@ -99,7 +99,7 @@ void RepeatedEnumFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer printer->Print( variables_, "foreach ($type_name$ element in $name$_) {\n" - " dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag(element);\n" + " dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag((int) element);\n" "}\n" "size += dataSize;\n"); int tagSize = internal::WireFormat::TagSize(descriptor_->number(), descriptor_->type()); -- cgit v1.2.3 From 96ddf01aed1a49d73a7fda50e28c431ffc977e5a Mon Sep 17 00:00:00 2001 From: Jon Skeet Date: Fri, 12 Jun 2015 09:53:12 +0100 Subject: Coded*Stream streamlining. Remove ICodedInputStream and ICodedOutputStream, and rewrite CodedInputStream and CodedOutputStream to be specific to the binary format. If we want to support text-based formats, that can be a whole different serialization mechanism. --- .../ProtocolBuffers.Test/CodedInputStreamTest.cs | 53 +- .../ProtocolBuffers.Test/CodedOutputStreamTest.cs | 43 +- .../TestProtos/UnittestImportProto3.cs | 18 +- .../TestProtos/UnittestImportPublicProto3.cs | 18 +- .../TestProtos/UnittestIssues.cs | 100 +- .../TestProtos/UnittestProto3.cs | 1000 +++++++------------- csharp/src/ProtocolBuffers/CodedInputStream.cs | 427 ++------- .../CodedOutputStream.ComputeSize.cs | 132 +-- csharp/src/ProtocolBuffers/CodedOutputStream.cs | 249 ++--- .../DescriptorProtos/DescriptorProtoFile.cs | 719 ++++++-------- csharp/src/ProtocolBuffers/Extensions.cs | 2 +- csharp/src/ProtocolBuffers/ICodedInputStream.cs | 293 ------ csharp/src/ProtocolBuffers/ICodedOutputStream.cs | 347 ------- csharp/src/ProtocolBuffers/IMessage.cs | 4 +- csharp/src/ProtocolBuffers/MessageParser.cs | 2 +- csharp/src/ProtocolBuffers/ProtocolBuffers.csproj | 2 - .../protobuf/compiler/csharp/csharp_enum_field.cc | 16 +- .../protobuf/compiler/csharp/csharp_message.cc | 17 +- .../compiler/csharp/csharp_message_field.cc | 3 +- .../compiler/csharp/csharp_primitive_field.cc | 16 +- .../compiler/csharp/csharp_repeated_enum_field.cc | 4 +- .../csharp/csharp_repeated_message_field.cc | 4 +- .../csharp/csharp_repeated_primitive_field.cc | 6 +- 23 files changed, 879 insertions(+), 2596 deletions(-) delete mode 100644 csharp/src/ProtocolBuffers/ICodedInputStream.cs delete mode 100644 csharp/src/ProtocolBuffers/ICodedOutputStream.cs (limited to 'src/google') diff --git a/csharp/src/ProtocolBuffers.Test/CodedInputStreamTest.cs b/csharp/src/ProtocolBuffers.Test/CodedInputStreamTest.cs index aa2da330..450662a6 100644 --- a/csharp/src/ProtocolBuffers.Test/CodedInputStreamTest.cs +++ b/csharp/src/ProtocolBuffers.Test/CodedInputStreamTest.cs @@ -336,13 +336,11 @@ namespace Google.Protobuf CodedInputStream input = CodedInputStream.CreateInstance(ms); uint testtag; - string ignore; - Assert.IsTrue(input.ReadTag(out testtag, out ignore)); + Assert.IsTrue(input.ReadTag(out testtag)); Assert.AreEqual(tag, testtag); - ByteString bytes = null; // TODO(jonskeet): Should this be ArgumentNullException instead? - Assert.Throws(() => input.ReadBytes(ref bytes)); + Assert.Throws(() => input.ReadBytes()); } private static TestRecursiveMessage MakeRecursiveMessage(int depth) @@ -435,13 +433,10 @@ namespace Google.Protobuf CodedInputStream input = CodedInputStream.CreateInstance(ms); - uint testtag; - string ignored; - - Assert.IsTrue(input.ReadTag(out testtag, out ignored)); - Assert.AreEqual(tag, testtag); - string text = null; - input.ReadString(ref text); + uint actualTag; + Assert.IsTrue(input.ReadTag(out actualTag)); + Assert.AreEqual(tag, actualTag); + string text = input.ReadString(); Assert.AreEqual('\ufffd', text[0]); } @@ -473,11 +468,8 @@ namespace Google.Protobuf { byte[] bytes = new byte[10] { 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01 }; CodedInputStream input = CodedInputStream.CreateInstance(bytes); - int val = 0; - - Assert.IsTrue(input.ReadEnum(ref val)); + Assert.AreEqual((int)TestNegEnum.Value, input.ReadEnum()); Assert.IsTrue(input.IsAtEnd); - Assert.AreEqual((int) TestNegEnum.Value, val); } [Test] @@ -487,17 +479,16 @@ namespace Google.Protobuf int msgSize = 1 + 1 + arraySize; byte[] bytes = new byte[msgSize]; CodedOutputStream output = CodedOutputStream.CreateInstance(bytes); - output.WritePackedInt32Array(8, "", new RepeatedField { 0, -1, -2, -3, -4, -5 }); + output.WritePackedInt32Array(8, new RepeatedField { 0, -1, -2, -3, -4, -5 }); Assert.AreEqual(0, output.SpaceLeft); CodedInputStream input = CodedInputStream.CreateInstance(bytes); uint tag; - string name; - Assert.IsTrue(input.ReadTag(out tag, out name)); + Assert.IsTrue(input.ReadTag(out tag)); List values = new List(); - input.ReadEnumArray(tag, name, values); + input.ReadEnumArray(tag, values); Assert.AreEqual(6, values.Count); Assert.AreEqual(TestNegEnum.None, values[0]); @@ -512,17 +503,16 @@ namespace Google.Protobuf int msgSize = arraySize; byte[] bytes = new byte[msgSize]; CodedOutputStream output = CodedOutputStream.CreateInstance(bytes); - output.WriteInt32Array(8, "", new RepeatedField { 0, -1, -2, -3, -4, -5 }); + output.WriteInt32Array(8, new RepeatedField { 0, -1, -2, -3, -4, -5 }); Assert.AreEqual(0, output.SpaceLeft); CodedInputStream input = CodedInputStream.CreateInstance(bytes); uint tag; - string name; - Assert.IsTrue(input.ReadTag(out tag, out name)); + Assert.IsTrue(input.ReadTag(out tag)); List values = new List(); - input.ReadEnumArray(tag, name, values); + input.ReadEnumArray(tag, values); Assert.AreEqual(6, values.Count); Assert.AreEqual(TestNegEnum.None, values[0]); @@ -537,26 +527,21 @@ namespace Google.Protobuf using (var ms = new MemoryStream()) { CodedOutputStream output = CodedOutputStream.CreateInstance(ms); - output.WriteField(FieldType.Bytes, 1, "bytes", ByteString.CopyFrom(new byte[100])); - output.WriteField(FieldType.Bytes, 2, "bytes", ByteString.CopyFrom(new byte[100])); + output.WriteBytes(1, ByteString.CopyFrom(new byte[100])); + output.WriteBytes(2, ByteString.CopyFrom(new byte[100])); output.Flush(); ms.Position = 0; CodedInputStream input = CodedInputStream.CreateInstance(ms, new byte[ms.Length / 2]); uint tag; - string ignore; - ByteString value; - - Assert.IsTrue(input.ReadTag(out tag, out ignore)); + Assert.IsTrue(input.ReadTag(out tag)); Assert.AreEqual(1, WireFormat.GetTagFieldNumber(tag)); - value = ByteString.Empty; - Assert.IsTrue(input.ReadBytes(ref value) && value.Length == 100); + Assert.AreEqual(100, input.ReadBytes().Length); - Assert.IsTrue(input.ReadTag(out tag, out ignore)); + Assert.IsTrue(input.ReadTag(out tag)); Assert.AreEqual(2, WireFormat.GetTagFieldNumber(tag)); - value = ByteString.Empty; - Assert.IsTrue(input.ReadBytes(ref value) && value.Length == 100); + Assert.AreEqual(100, input.ReadBytes().Length); } } } diff --git a/csharp/src/ProtocolBuffers.Test/CodedOutputStreamTest.cs b/csharp/src/ProtocolBuffers.Test/CodedOutputStreamTest.cs index fcbb7f8d..682c005a 100644 --- a/csharp/src/ProtocolBuffers.Test/CodedOutputStreamTest.cs +++ b/csharp/src/ProtocolBuffers.Test/CodedOutputStreamTest.cs @@ -316,7 +316,7 @@ namespace Google.Protobuf byte[] bytes = new byte[11]; CodedOutputStream output = CodedOutputStream.CreateInstance(bytes); - output.WriteEnum(8, "", (int) TestNegEnum.Value); + output.WriteEnum(8, (int) TestNegEnum.Value); Assert.AreEqual(0, output.SpaceLeft); //fyi, 0x40 == 0x08 << 3 + 0, field num + wire format shift @@ -330,18 +330,17 @@ namespace Google.Protobuf int msgSize = 1 + 1 + arraySize; byte[] bytes = new byte[msgSize]; CodedOutputStream output = CodedOutputStream.CreateInstance(bytes); - output.WritePackedEnumArray(8, "", new RepeatedField { + output.WritePackedEnumArray(8, new RepeatedField { 0, (TestNegEnum) (-1), TestNegEnum.Value, (TestNegEnum) (-3), (TestNegEnum) (-4), (TestNegEnum) (-5) }); Assert.AreEqual(0, output.SpaceLeft); CodedInputStream input = CodedInputStream.CreateInstance(bytes); uint tag; - string name; - Assert.IsTrue(input.ReadTag(out tag, out name)); + Assert.IsTrue(input.ReadTag(out tag)); List values = new List(); - input.ReadInt32Array(tag, name, values); + input.ReadInt32Array(tag, values); Assert.AreEqual(6, values.Count); for (int i = 0; i > -6; i--) @@ -355,17 +354,16 @@ namespace Google.Protobuf int msgSize = arraySize; byte[] bytes = new byte[msgSize]; CodedOutputStream output = CodedOutputStream.CreateInstance(bytes); - output.WriteEnumArray(8, "", new RepeatedField { + output.WriteEnumArray(8, new RepeatedField { 0, (TestNegEnum) (-1), TestNegEnum.Value, (TestNegEnum) (-3), (TestNegEnum) (-4), (TestNegEnum) (-5) }); Assert.AreEqual(0, output.SpaceLeft); CodedInputStream input = CodedInputStream.CreateInstance(bytes); uint tag; - string name; - Assert.IsTrue(input.ReadTag(out tag, out name)); + Assert.IsTrue(input.ReadTag(out tag)); List values = new List(); - input.ReadInt32Array(tag, name, values); + input.ReadInt32Array(tag, values); Assert.AreEqual(6, values.Count); for (int i = 0; i > -6; i--) @@ -425,16 +423,14 @@ namespace Google.Protobuf { CodedInputStream cin = CodedInputStream.CreateInstance(new MemoryStream(bytes), new byte[50]); uint tag; - int intValue = 0; - string ignore; Assert.AreEqual(0, cin.Position); // Field 1: - Assert.IsTrue(cin.ReadTag(out tag, out ignore) && tag >> 3 == 1); + Assert.IsTrue(cin.ReadTag(out tag) && tag >> 3 == 1); Assert.AreEqual(1, cin.Position); - Assert.IsTrue(cin.ReadInt32(ref intValue) && intValue == 500); + Assert.AreEqual(500, cin.ReadInt32()); Assert.AreEqual(3, cin.Position); //Field 2: - Assert.IsTrue(cin.ReadTag(out tag, out ignore) && tag >> 3 == 2); + Assert.IsTrue(cin.ReadTag(out tag) && tag >> 3 == 2); Assert.AreEqual(4, cin.Position); uint childlen = cin.ReadRawVarint32(); Assert.AreEqual(120u, childlen); @@ -444,30 +440,31 @@ namespace Google.Protobuf // Now we are reading child message { // Field 11: numeric value: 500 - Assert.IsTrue(cin.ReadTag(out tag, out ignore) && tag >> 3 == 11); + Assert.IsTrue(cin.ReadTag(out tag) && tag >> 3 == 11); Assert.AreEqual(6, cin.Position); - Assert.IsTrue(cin.ReadInt32(ref intValue) && intValue == 500); + Assert.AreEqual(500, cin.ReadInt32()); Assert.AreEqual(8, cin.Position); //Field 12: length delimited 120 bytes - Assert.IsTrue(cin.ReadTag(out tag, out ignore) && tag >> 3 == 12); + Assert.IsTrue(cin.ReadTag(out tag) && tag >> 3 == 12); Assert.AreEqual(9, cin.Position); - ByteString bstr = null; - Assert.IsTrue(cin.ReadBytes(ref bstr) && bstr.Length == 110 && bstr.ToByteArray()[109] == 109); + ByteString bstr = cin.ReadBytes(); + Assert.AreEqual(110, bstr.Length); + Assert.AreEqual((byte) 109, bstr[109]); Assert.AreEqual(120, cin.Position); // Field 13: fixed numeric value: 501 - Assert.IsTrue(cin.ReadTag(out tag, out ignore) && tag >> 3 == 13); + Assert.IsTrue(cin.ReadTag(out tag) && tag >> 3 == 13); // ROK - Previously broken here, this returned 126 failing to account for bufferSizeAfterLimit Assert.AreEqual(121, cin.Position); - Assert.IsTrue(cin.ReadSFixed32(ref intValue) && intValue == 501); + Assert.AreEqual(501, cin.ReadSFixed32()); Assert.AreEqual(125, cin.Position); Assert.IsTrue(cin.IsAtEnd); } cin.PopLimit(oldlimit); Assert.AreEqual(125, cin.Position); // Field 3: fixed numeric value: 501 - Assert.IsTrue(cin.ReadTag(out tag, out ignore) && tag >> 3 == 3); + Assert.IsTrue(cin.ReadTag(out tag) && tag >> 3 == 3); Assert.AreEqual(126, cin.Position); - Assert.IsTrue(cin.ReadSFixed32(ref intValue) && intValue == 501); + Assert.AreEqual(501, cin.ReadSFixed32()); Assert.AreEqual(130, cin.Position); Assert.IsTrue(cin.IsAtEnd); } diff --git a/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImportProto3.cs b/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImportProto3.cs index 4b62794a..1bd4e22b 100644 --- a/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImportProto3.cs +++ b/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImportProto3.cs @@ -107,10 +107,9 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (D != 0) { - output.WriteInt32(1, fieldNames[0], D); + output.WriteInt32(1, D); } } @@ -130,16 +129,9 @@ namespace Google.Protobuf.TestProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -149,7 +141,7 @@ namespace Google.Protobuf.TestProtos { } break; case 8: { - input.ReadInt32(ref d_); + d_ = input.ReadInt32(); break; } } diff --git a/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImportPublicProto3.cs b/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImportPublicProto3.cs index 2f7f8699..32123d53 100644 --- a/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImportPublicProto3.cs +++ b/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImportPublicProto3.cs @@ -92,10 +92,9 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (E != 0) { - output.WriteInt32(1, fieldNames[0], E); + output.WriteInt32(1, E); } } @@ -115,16 +114,9 @@ namespace Google.Protobuf.TestProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -134,7 +126,7 @@ namespace Google.Protobuf.TestProtos { } break; case 8: { - input.ReadInt32(ref e_); + e_ = input.ReadInt32(); break; } } diff --git a/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestIssues.cs b/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestIssues.cs index 14ca78a4..d8c8995b 100644 --- a/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestIssues.cs +++ b/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestIssues.cs @@ -153,13 +153,12 @@ namespace UnitTest.Issues.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (Value != global::UnitTest.Issues.TestProtos.NegativeEnum.NEGATIVE_ENUM_ZERO) { - output.WriteEnum(1, fieldNames[1], (int) Value); + output.WriteEnum(1, (int) Value); } - output.WriteEnumArray(2, fieldNames[2], values_); - output.WritePackedEnumArray(3, fieldNames[0], packedValues_); + output.WriteEnumArray(2, values_); + output.WritePackedEnumArray(3, packedValues_); } public int CalculateSize() { @@ -201,16 +200,9 @@ namespace UnitTest.Issues.TestProtos { packedValues_.Add(other.packedValues_); } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -220,18 +212,17 @@ namespace UnitTest.Issues.TestProtos { } break; case 8: { - int tmp = 0; - input.ReadEnum(ref tmp); - value_ = (global::UnitTest.Issues.TestProtos.NegativeEnum) tmp;break; + value_ = (global::UnitTest.Issues.TestProtos.NegativeEnum) input.ReadEnum(); + break; } case 18: case 16: { - input.ReadEnumArray(tag, fieldName, values_); + input.ReadEnumArray(tag, values_); break; } case 26: case 24: { - input.ReadEnumArray(tag, fieldName, packedValues_); + input.ReadEnumArray(tag, packedValues_); break; } } @@ -278,8 +269,7 @@ namespace UnitTest.Issues.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { } public int CalculateSize() { @@ -292,16 +282,9 @@ namespace UnitTest.Issues.TestProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -412,20 +395,19 @@ namespace UnitTest.Issues.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (PrimitiveValue != 0) { - output.WriteInt32(1, fieldNames[5], PrimitiveValue); + output.WriteInt32(1, PrimitiveValue); } - output.WritePackedInt32Array(2, fieldNames[4], primitiveArray_); + output.WritePackedInt32Array(2, primitiveArray_); if (messageValue_ != null) { - output.WriteMessage(3, fieldNames[3], MessageValue); + output.WriteMessage(3, MessageValue); } - output.WriteMessageArray(4, fieldNames[2], messageArray_); + output.WriteMessageArray(4, messageArray_); if (EnumValue != global::UnitTest.Issues.TestProtos.DeprecatedEnum.DEPRECATED_ZERO) { - output.WriteEnum(5, fieldNames[1], (int) EnumValue); + output.WriteEnum(5, (int) EnumValue); } - output.WritePackedEnumArray(6, fieldNames[0], enumArray_); + output.WritePackedEnumArray(6, enumArray_); } public int CalculateSize() { @@ -486,16 +468,9 @@ namespace UnitTest.Issues.TestProtos { enumArray_.Add(other.enumArray_); } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -505,12 +480,12 @@ namespace UnitTest.Issues.TestProtos { } break; case 8: { - input.ReadInt32(ref primitiveValue_); + primitiveValue_ = input.ReadInt32(); break; } case 18: case 16: { - input.ReadInt32Array(tag, fieldName, primitiveArray_); + input.ReadInt32Array(tag, primitiveArray_); break; } case 26: { @@ -521,17 +496,16 @@ namespace UnitTest.Issues.TestProtos { break; } case 34: { - input.ReadMessageArray(tag, fieldName, messageArray_, global::UnitTest.Issues.TestProtos.DeprecatedChild.Parser); + input.ReadMessageArray(tag, messageArray_, global::UnitTest.Issues.TestProtos.DeprecatedChild.Parser); break; } case 40: { - int tmp = 0; - input.ReadEnum(ref tmp); - enumValue_ = (global::UnitTest.Issues.TestProtos.DeprecatedEnum) tmp;break; + enumValue_ = (global::UnitTest.Issues.TestProtos.DeprecatedEnum) input.ReadEnum(); + break; } case 50: case 48: { - input.ReadEnumArray(tag, fieldName, enumArray_); + input.ReadEnumArray(tag, enumArray_); break; } } @@ -588,10 +562,9 @@ namespace UnitTest.Issues.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (Item != 0) { - output.WriteInt32(1, fieldNames[0], Item); + output.WriteInt32(1, Item); } } @@ -611,16 +584,9 @@ namespace UnitTest.Issues.TestProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -630,7 +596,7 @@ namespace UnitTest.Issues.TestProtos { } break; case 8: { - input.ReadInt32(ref item_); + item_ = input.ReadInt32(); break; } } diff --git a/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestProto3.cs b/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestProto3.cs index 3e5bb8b6..4c4dabab 100644 --- a/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestProto3.cs +++ b/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestProto3.cs @@ -888,107 +888,106 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (SingleInt32 != 0) { - output.WriteInt32(1, fieldNames[36], SingleInt32); + output.WriteInt32(1, SingleInt32); } if (SingleInt64 != 0L) { - output.WriteInt64(2, fieldNames[37], SingleInt64); + output.WriteInt64(2, SingleInt64); } if (SingleUint32 != 0) { - output.WriteUInt32(3, fieldNames[46], SingleUint32); + output.WriteUInt32(3, SingleUint32); } if (SingleUint64 != 0UL) { - output.WriteUInt64(4, fieldNames[47], SingleUint64); + output.WriteUInt64(4, SingleUint64); } if (SingleSint32 != 0) { - output.WriteSInt32(5, fieldNames[43], SingleSint32); + output.WriteSInt32(5, SingleSint32); } if (SingleSint64 != 0L) { - output.WriteSInt64(6, fieldNames[44], SingleSint64); + output.WriteSInt64(6, SingleSint64); } if (SingleFixed32 != 0) { - output.WriteFixed32(7, fieldNames[29], SingleFixed32); + output.WriteFixed32(7, SingleFixed32); } if (SingleFixed64 != 0UL) { - output.WriteFixed64(8, fieldNames[30], SingleFixed64); + output.WriteFixed64(8, SingleFixed64); } if (SingleSfixed32 != 0) { - output.WriteSFixed32(9, fieldNames[41], SingleSfixed32); + output.WriteSFixed32(9, SingleSfixed32); } if (SingleSfixed64 != 0L) { - output.WriteSFixed64(10, fieldNames[42], SingleSfixed64); + output.WriteSFixed64(10, SingleSfixed64); } if (SingleFloat != 0F) { - output.WriteFloat(11, fieldNames[31], SingleFloat); + output.WriteFloat(11, SingleFloat); } if (SingleDouble != 0D) { - output.WriteDouble(12, fieldNames[28], SingleDouble); + output.WriteDouble(12, SingleDouble); } if (SingleBool != false) { - output.WriteBool(13, fieldNames[26], SingleBool); + output.WriteBool(13, SingleBool); } if (SingleString != "") { - output.WriteString(14, fieldNames[45], SingleString); + output.WriteString(14, SingleString); } if (SingleBytes != pb::ByteString.Empty) { - output.WriteBytes(15, fieldNames[27], SingleBytes); + output.WriteBytes(15, SingleBytes); } if (singleNestedMessage_ != null) { - output.WriteMessage(18, fieldNames[39], SingleNestedMessage); + output.WriteMessage(18, SingleNestedMessage); } if (singleForeignMessage_ != null) { - output.WriteMessage(19, fieldNames[33], SingleForeignMessage); + output.WriteMessage(19, SingleForeignMessage); } if (singleImportMessage_ != null) { - output.WriteMessage(20, fieldNames[35], SingleImportMessage); + output.WriteMessage(20, SingleImportMessage); } if (SingleNestedEnum != global::Google.Protobuf.TestProtos.TestAllTypes.Types.NestedEnum.NESTED_ENUM_UNSPECIFIED) { - output.WriteEnum(21, fieldNames[38], (int) SingleNestedEnum); + output.WriteEnum(21, (int) SingleNestedEnum); } if (SingleForeignEnum != global::Google.Protobuf.TestProtos.ForeignEnum.FOREIGN_UNSPECIFIED) { - output.WriteEnum(22, fieldNames[32], (int) SingleForeignEnum); + output.WriteEnum(22, (int) SingleForeignEnum); } if (SingleImportEnum != global::Google.Protobuf.TestProtos.ImportEnum.IMPORT_ENUM_UNSPECIFIED) { - output.WriteEnum(23, fieldNames[34], (int) SingleImportEnum); + output.WriteEnum(23, (int) SingleImportEnum); } if (singlePublicImportMessage_ != null) { - output.WriteMessage(26, fieldNames[40], SinglePublicImportMessage); - } - output.WritePackedInt32Array(31, fieldNames[14], repeatedInt32_); - output.WritePackedInt64Array(32, fieldNames[15], repeatedInt64_); - output.WritePackedUInt32Array(33, fieldNames[24], repeatedUint32_); - output.WritePackedUInt64Array(34, fieldNames[25], repeatedUint64_); - output.WritePackedSInt32Array(35, fieldNames[21], repeatedSint32_); - output.WritePackedSInt64Array(36, fieldNames[22], repeatedSint64_); - output.WritePackedFixed32Array(37, fieldNames[7], repeatedFixed32_); - output.WritePackedFixed64Array(38, fieldNames[8], repeatedFixed64_); - output.WritePackedSFixed32Array(39, fieldNames[19], repeatedSfixed32_); - output.WritePackedSFixed64Array(40, fieldNames[20], repeatedSfixed64_); - output.WritePackedFloatArray(41, fieldNames[9], repeatedFloat_); - output.WritePackedDoubleArray(42, fieldNames[6], repeatedDouble_); - output.WritePackedBoolArray(43, fieldNames[4], repeatedBool_); - output.WriteStringArray(44, fieldNames[23], repeatedString_); - output.WriteBytesArray(45, fieldNames[5], repeatedBytes_); - output.WriteMessageArray(48, fieldNames[17], repeatedNestedMessage_); - output.WriteMessageArray(49, fieldNames[11], repeatedForeignMessage_); - output.WriteMessageArray(50, fieldNames[13], repeatedImportMessage_); - output.WritePackedEnumArray(51, fieldNames[16], repeatedNestedEnum_); - output.WritePackedEnumArray(52, fieldNames[10], repeatedForeignEnum_); - output.WritePackedEnumArray(53, fieldNames[12], repeatedImportEnum_); - output.WriteMessageArray(54, fieldNames[18], repeatedPublicImportMessage_); + output.WriteMessage(26, SinglePublicImportMessage); + } + output.WritePackedInt32Array(31, repeatedInt32_); + output.WritePackedInt64Array(32, repeatedInt64_); + output.WritePackedUInt32Array(33, repeatedUint32_); + output.WritePackedUInt64Array(34, repeatedUint64_); + output.WritePackedSInt32Array(35, repeatedSint32_); + output.WritePackedSInt64Array(36, repeatedSint64_); + output.WritePackedFixed32Array(37, repeatedFixed32_); + output.WritePackedFixed64Array(38, repeatedFixed64_); + output.WritePackedSFixed32Array(39, repeatedSfixed32_); + output.WritePackedSFixed64Array(40, repeatedSfixed64_); + output.WritePackedFloatArray(41, repeatedFloat_); + output.WritePackedDoubleArray(42, repeatedDouble_); + output.WritePackedBoolArray(43, repeatedBool_); + output.WriteStringArray(44, repeatedString_); + output.WriteBytesArray(45, repeatedBytes_); + output.WriteMessageArray(48, repeatedNestedMessage_); + output.WriteMessageArray(49, repeatedForeignMessage_); + output.WriteMessageArray(50, repeatedImportMessage_); + output.WritePackedEnumArray(51, repeatedNestedEnum_); + output.WritePackedEnumArray(52, repeatedForeignEnum_); + output.WritePackedEnumArray(53, repeatedImportEnum_); + output.WriteMessageArray(54, repeatedPublicImportMessage_); if (oneofFieldCase_ == OneofFieldOneofCase.OneofUint32) { - output.WriteUInt32(111, fieldNames[3], OneofUint32); + output.WriteUInt32(111, OneofUint32); } if (oneofFieldCase_ == OneofFieldOneofCase.OneofNestedMessage) { - output.WriteMessage(112, fieldNames[1], OneofNestedMessage); + output.WriteMessage(112, OneofNestedMessage); } if (oneofFieldCase_ == OneofFieldOneofCase.OneofString) { - output.WriteString(113, fieldNames[2], OneofString); + output.WriteString(113, OneofString); } if (oneofFieldCase_ == OneofFieldOneofCase.OneofBytes) { - output.WriteBytes(114, fieldNames[0], OneofBytes); + output.WriteBytes(114, OneofBytes); } } @@ -1372,16 +1371,9 @@ namespace Google.Protobuf.TestProtos { } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -1391,63 +1383,63 @@ namespace Google.Protobuf.TestProtos { } break; case 8: { - input.ReadInt32(ref singleInt32_); + singleInt32_ = input.ReadInt32(); break; } case 16: { - input.ReadInt64(ref singleInt64_); + singleInt64_ = input.ReadInt64(); break; } case 24: { - input.ReadUInt32(ref singleUint32_); + singleUint32_ = input.ReadUInt32(); break; } case 32: { - input.ReadUInt64(ref singleUint64_); + singleUint64_ = input.ReadUInt64(); break; } case 40: { - input.ReadSInt32(ref singleSint32_); + singleSint32_ = input.ReadSInt32(); break; } case 48: { - input.ReadSInt64(ref singleSint64_); + singleSint64_ = input.ReadSInt64(); break; } case 61: { - input.ReadFixed32(ref singleFixed32_); + singleFixed32_ = input.ReadFixed32(); break; } case 65: { - input.ReadFixed64(ref singleFixed64_); + singleFixed64_ = input.ReadFixed64(); break; } case 77: { - input.ReadSFixed32(ref singleSfixed32_); + singleSfixed32_ = input.ReadSFixed32(); break; } case 81: { - input.ReadSFixed64(ref singleSfixed64_); + singleSfixed64_ = input.ReadSFixed64(); break; } case 93: { - input.ReadFloat(ref singleFloat_); + singleFloat_ = input.ReadFloat(); break; } case 97: { - input.ReadDouble(ref singleDouble_); + singleDouble_ = input.ReadDouble(); break; } case 104: { - input.ReadBool(ref singleBool_); + singleBool_ = input.ReadBool(); break; } case 114: { - input.ReadString(ref singleString_); + singleString_ = input.ReadString(); break; } case 122: { - input.ReadBytes(ref singleBytes_); + singleBytes_ = input.ReadBytes(); break; } case 146: { @@ -1472,19 +1464,16 @@ namespace Google.Protobuf.TestProtos { break; } case 168: { - int tmp = 0; - input.ReadEnum(ref tmp); - singleNestedEnum_ = (global::Google.Protobuf.TestProtos.TestAllTypes.Types.NestedEnum) tmp;break; + singleNestedEnum_ = (global::Google.Protobuf.TestProtos.TestAllTypes.Types.NestedEnum) input.ReadEnum(); + break; } case 176: { - int tmp = 0; - input.ReadEnum(ref tmp); - singleForeignEnum_ = (global::Google.Protobuf.TestProtos.ForeignEnum) tmp;break; + singleForeignEnum_ = (global::Google.Protobuf.TestProtos.ForeignEnum) input.ReadEnum(); + break; } case 184: { - int tmp = 0; - input.ReadEnum(ref tmp); - singleImportEnum_ = (global::Google.Protobuf.TestProtos.ImportEnum) tmp;break; + singleImportEnum_ = (global::Google.Protobuf.TestProtos.ImportEnum) input.ReadEnum(); + break; } case 210: { if (singlePublicImportMessage_ == null) { @@ -1495,114 +1484,111 @@ namespace Google.Protobuf.TestProtos { } case 250: case 248: { - input.ReadInt32Array(tag, fieldName, repeatedInt32_); + input.ReadInt32Array(tag, repeatedInt32_); break; } case 258: case 256: { - input.ReadInt64Array(tag, fieldName, repeatedInt64_); + input.ReadInt64Array(tag, repeatedInt64_); break; } case 266: case 264: { - input.ReadUInt32Array(tag, fieldName, repeatedUint32_); + input.ReadUInt32Array(tag, repeatedUint32_); break; } case 274: case 272: { - input.ReadUInt64Array(tag, fieldName, repeatedUint64_); + input.ReadUInt64Array(tag, repeatedUint64_); break; } case 282: case 280: { - input.ReadSInt32Array(tag, fieldName, repeatedSint32_); + input.ReadSInt32Array(tag, repeatedSint32_); break; } case 290: case 288: { - input.ReadSInt64Array(tag, fieldName, repeatedSint64_); + input.ReadSInt64Array(tag, repeatedSint64_); break; } case 298: case 301: { - input.ReadFixed32Array(tag, fieldName, repeatedFixed32_); + input.ReadFixed32Array(tag, repeatedFixed32_); break; } case 306: case 305: { - input.ReadFixed64Array(tag, fieldName, repeatedFixed64_); + input.ReadFixed64Array(tag, repeatedFixed64_); break; } case 314: case 317: { - input.ReadSFixed32Array(tag, fieldName, repeatedSfixed32_); + input.ReadSFixed32Array(tag, repeatedSfixed32_); break; } case 322: case 321: { - input.ReadSFixed64Array(tag, fieldName, repeatedSfixed64_); + input.ReadSFixed64Array(tag, repeatedSfixed64_); break; } case 330: case 333: { - input.ReadFloatArray(tag, fieldName, repeatedFloat_); + input.ReadFloatArray(tag, repeatedFloat_); break; } case 338: case 337: { - input.ReadDoubleArray(tag, fieldName, repeatedDouble_); + input.ReadDoubleArray(tag, repeatedDouble_); break; } case 346: case 344: { - input.ReadBoolArray(tag, fieldName, repeatedBool_); + input.ReadBoolArray(tag, repeatedBool_); break; } case 354: { - input.ReadStringArray(tag, fieldName, repeatedString_); + input.ReadStringArray(tag, repeatedString_); break; } case 362: { - input.ReadBytesArray(tag, fieldName, repeatedBytes_); + input.ReadBytesArray(tag, repeatedBytes_); break; } case 386: { - input.ReadMessageArray(tag, fieldName, repeatedNestedMessage_, global::Google.Protobuf.TestProtos.TestAllTypes.Types.NestedMessage.Parser); + input.ReadMessageArray(tag, repeatedNestedMessage_, global::Google.Protobuf.TestProtos.TestAllTypes.Types.NestedMessage.Parser); break; } case 394: { - input.ReadMessageArray(tag, fieldName, repeatedForeignMessage_, global::Google.Protobuf.TestProtos.ForeignMessage.Parser); + input.ReadMessageArray(tag, repeatedForeignMessage_, global::Google.Protobuf.TestProtos.ForeignMessage.Parser); break; } case 402: { - input.ReadMessageArray(tag, fieldName, repeatedImportMessage_, global::Google.Protobuf.TestProtos.ImportMessage.Parser); + input.ReadMessageArray(tag, repeatedImportMessage_, global::Google.Protobuf.TestProtos.ImportMessage.Parser); break; } case 410: case 408: { - input.ReadEnumArray(tag, fieldName, repeatedNestedEnum_); + input.ReadEnumArray(tag, repeatedNestedEnum_); break; } case 418: case 416: { - input.ReadEnumArray(tag, fieldName, repeatedForeignEnum_); + input.ReadEnumArray(tag, repeatedForeignEnum_); break; } case 426: case 424: { - input.ReadEnumArray(tag, fieldName, repeatedImportEnum_); + input.ReadEnumArray(tag, repeatedImportEnum_); break; } case 434: { - input.ReadMessageArray(tag, fieldName, repeatedPublicImportMessage_, global::Google.Protobuf.TestProtos.PublicImportMessage.Parser); + input.ReadMessageArray(tag, repeatedPublicImportMessage_, global::Google.Protobuf.TestProtos.PublicImportMessage.Parser); break; } case 888: { - uint value = 0; - if (input.ReadUInt32(ref value)) { - oneofField_ = value; - oneofFieldCase_ = OneofFieldOneofCase.OneofUint32; - } + oneofField_ = input.ReadUInt32() + ;oneofFieldCase_ = OneofFieldOneofCase.OneofUint32; break; } case 898: { @@ -1615,19 +1601,13 @@ namespace Google.Protobuf.TestProtos { break; } case 906: { - string value = ""; - if (input.ReadString(ref value)) { - oneofField_ = value; - oneofFieldCase_ = OneofFieldOneofCase.OneofString; - } + oneofField_ = input.ReadString() + ;oneofFieldCase_ = OneofFieldOneofCase.OneofString; break; } case 914: { - pb::ByteString value = pb::ByteString.Empty; - if (input.ReadBytes(ref value)) { - oneofField_ = value; - oneofFieldCase_ = OneofFieldOneofCase.OneofBytes; - } + oneofField_ = input.ReadBytes() + ;oneofFieldCase_ = OneofFieldOneofCase.OneofBytes; break; } } @@ -1693,10 +1673,9 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (Bb != 0) { - output.WriteInt32(1, fieldNames[0], Bb); + output.WriteInt32(1, Bb); } } @@ -1716,16 +1695,9 @@ namespace Google.Protobuf.TestProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -1735,7 +1707,7 @@ namespace Google.Protobuf.TestProtos { } break; case 8: { - input.ReadInt32(ref bb_); + bb_ = input.ReadInt32(); break; } } @@ -1811,15 +1783,14 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (child_ != null) { - output.WriteMessage(1, fieldNames[0], Child); + output.WriteMessage(1, Child); } if (payload_ != null) { - output.WriteMessage(2, fieldNames[1], Payload); + output.WriteMessage(2, Payload); } - output.WriteMessageArray(3, fieldNames[2], repeatedChild_); + output.WriteMessageArray(3, repeatedChild_); } public int CalculateSize() { @@ -1854,16 +1825,9 @@ namespace Google.Protobuf.TestProtos { repeatedChild_.Add(other.repeatedChild_); } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -1887,7 +1851,7 @@ namespace Google.Protobuf.TestProtos { break; } case 26: { - input.ReadMessageArray(tag, fieldName, repeatedChild_, global::Google.Protobuf.TestProtos.NestedTestAllTypes.Parser); + input.ReadMessageArray(tag, repeatedChild_, global::Google.Protobuf.TestProtos.NestedTestAllTypes.Parser); break; } } @@ -1945,10 +1909,9 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (DeprecatedInt32 != 0) { - output.WriteInt32(1, fieldNames[0], DeprecatedInt32); + output.WriteInt32(1, DeprecatedInt32); } } @@ -1968,16 +1931,9 @@ namespace Google.Protobuf.TestProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -1987,7 +1943,7 @@ namespace Google.Protobuf.TestProtos { } break; case 8: { - input.ReadInt32(ref deprecatedInt32_); + deprecatedInt32_ = input.ReadInt32(); break; } } @@ -2044,10 +2000,9 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (C != 0) { - output.WriteInt32(1, fieldNames[0], C); + output.WriteInt32(1, C); } } @@ -2067,16 +2022,9 @@ namespace Google.Protobuf.TestProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -2086,7 +2034,7 @@ namespace Google.Protobuf.TestProtos { } break; case 8: { - input.ReadInt32(ref c_); + c_ = input.ReadInt32(); break; } } @@ -2133,8 +2081,7 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { } public int CalculateSize() { @@ -2147,16 +2094,9 @@ namespace Google.Protobuf.TestProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -2217,10 +2157,9 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (foreignNested_ != null) { - output.WriteMessage(1, fieldNames[0], ForeignNested); + output.WriteMessage(1, ForeignNested); } } @@ -2243,16 +2182,9 @@ namespace Google.Protobuf.TestProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -2332,13 +2264,12 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (A != 0) { - output.WriteInt32(1, fieldNames[0], A); + output.WriteInt32(1, A); } if (Bb != 0) { - output.WriteInt32(268435455, fieldNames[1], Bb); + output.WriteInt32(268435455, Bb); } } @@ -2364,16 +2295,9 @@ namespace Google.Protobuf.TestProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -2383,11 +2307,11 @@ namespace Google.Protobuf.TestProtos { } break; case 8: { - input.ReadInt32(ref a_); + a_ = input.ReadInt32(); break; } case 2147483640: { - input.ReadInt32(ref bb_); + bb_ = input.ReadInt32(); break; } } @@ -2452,13 +2376,12 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (a_ != null) { - output.WriteMessage(1, fieldNames[0], A); + output.WriteMessage(1, A); } if (I != 0) { - output.WriteInt32(2, fieldNames[1], I); + output.WriteInt32(2, I); } } @@ -2487,16 +2410,9 @@ namespace Google.Protobuf.TestProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -2513,7 +2429,7 @@ namespace Google.Protobuf.TestProtos { break; } case 16: { - input.ReadInt32(ref i_); + i_ = input.ReadInt32(); break; } } @@ -2568,10 +2484,9 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (bb_ != null) { - output.WriteMessage(1, fieldNames[0], Bb); + output.WriteMessage(1, Bb); } } @@ -2594,16 +2509,9 @@ namespace Google.Protobuf.TestProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -2681,13 +2589,12 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (a_ != null) { - output.WriteMessage(1, fieldNames[0], A); + output.WriteMessage(1, A); } if (OptionalInt32 != 0) { - output.WriteInt32(2, fieldNames[1], OptionalInt32); + output.WriteInt32(2, OptionalInt32); } } @@ -2716,16 +2623,9 @@ namespace Google.Protobuf.TestProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -2742,7 +2642,7 @@ namespace Google.Protobuf.TestProtos { break; } case 16: { - input.ReadInt32(ref optionalInt32_); + optionalInt32_ = input.ReadInt32(); break; } } @@ -2859,24 +2759,23 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (PrimitiveField != 0) { - output.WriteInt32(1, fieldNames[2], PrimitiveField); + output.WriteInt32(1, PrimitiveField); } if (StringField != "") { - output.WriteString(2, fieldNames[7], StringField); + output.WriteString(2, StringField); } if (EnumField != global::Google.Protobuf.TestProtos.ForeignEnum.FOREIGN_UNSPECIFIED) { - output.WriteEnum(3, fieldNames[0], (int) EnumField); + output.WriteEnum(3, (int) EnumField); } if (messageField_ != null) { - output.WriteMessage(4, fieldNames[1], MessageField); + output.WriteMessage(4, MessageField); } - output.WritePackedInt32Array(7, fieldNames[5], repeatedPrimitiveField_); - output.WriteStringArray(8, fieldNames[6], repeatedStringField_); - output.WritePackedEnumArray(9, fieldNames[3], repeatedEnumField_); - output.WriteMessageArray(10, fieldNames[4], repeatedMessageField_); + output.WritePackedInt32Array(7, repeatedPrimitiveField_); + output.WriteStringArray(8, repeatedStringField_); + output.WritePackedEnumArray(9, repeatedEnumField_); + output.WriteMessageArray(10, repeatedMessageField_); } public int CalculateSize() { @@ -2952,16 +2851,9 @@ namespace Google.Protobuf.TestProtos { repeatedMessageField_.Add(other.repeatedMessageField_); } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -2971,17 +2863,16 @@ namespace Google.Protobuf.TestProtos { } break; case 8: { - input.ReadInt32(ref primitiveField_); + primitiveField_ = input.ReadInt32(); break; } case 18: { - input.ReadString(ref stringField_); + stringField_ = input.ReadString(); break; } case 24: { - int tmp = 0; - input.ReadEnum(ref tmp); - enumField_ = (global::Google.Protobuf.TestProtos.ForeignEnum) tmp;break; + enumField_ = (global::Google.Protobuf.TestProtos.ForeignEnum) input.ReadEnum(); + break; } case 34: { if (messageField_ == null) { @@ -2992,20 +2883,20 @@ namespace Google.Protobuf.TestProtos { } case 58: case 56: { - input.ReadInt32Array(tag, fieldName, repeatedPrimitiveField_); + input.ReadInt32Array(tag, repeatedPrimitiveField_); break; } case 66: { - input.ReadStringArray(tag, fieldName, repeatedStringField_); + input.ReadStringArray(tag, repeatedStringField_); break; } case 74: case 72: { - input.ReadEnumArray(tag, fieldName, repeatedEnumField_); + input.ReadEnumArray(tag, repeatedEnumField_); break; } case 82: { - input.ReadMessageArray(tag, fieldName, repeatedMessageField_, global::Google.Protobuf.TestProtos.ForeignMessage.Parser); + input.ReadMessageArray(tag, repeatedMessageField_, global::Google.Protobuf.TestProtos.ForeignMessage.Parser); break; } } @@ -3090,19 +2981,18 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (MyInt != 0L) { - output.WriteInt64(1, fieldNames[1], MyInt); + output.WriteInt64(1, MyInt); } if (MyString != "") { - output.WriteString(11, fieldNames[2], MyString); + output.WriteString(11, MyString); } if (MyFloat != 0F) { - output.WriteFloat(101, fieldNames[0], MyFloat); + output.WriteFloat(101, MyFloat); } if (singleNestedMessage_ != null) { - output.WriteMessage(200, fieldNames[3], SingleNestedMessage); + output.WriteMessage(200, SingleNestedMessage); } } @@ -3143,16 +3033,9 @@ namespace Google.Protobuf.TestProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -3162,15 +3045,15 @@ namespace Google.Protobuf.TestProtos { } break; case 8: { - input.ReadInt64(ref myInt_); + myInt_ = input.ReadInt64(); break; } case 90: { - input.ReadString(ref myString_); + myString_ = input.ReadString(); break; } case 813: { - input.ReadFloat(ref myFloat_); + myFloat_ = input.ReadFloat(); break; } case 1602: { @@ -3245,13 +3128,12 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (Bb != 0) { - output.WriteInt32(1, fieldNames[0], Bb); + output.WriteInt32(1, Bb); } if (Oo != 0L) { - output.WriteInt64(2, fieldNames[1], Oo); + output.WriteInt64(2, Oo); } } @@ -3277,16 +3159,9 @@ namespace Google.Protobuf.TestProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -3296,11 +3171,11 @@ namespace Google.Protobuf.TestProtos { } break; case 8: { - input.ReadInt32(ref bb_); + bb_ = input.ReadInt32(); break; } case 16: { - input.ReadInt64(ref oo_); + oo_ = input.ReadInt64(); break; } } @@ -3362,10 +3237,9 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (SparseEnum != global::Google.Protobuf.TestProtos.TestSparseEnum.TEST_SPARSE_ENUM_UNSPECIFIED) { - output.WriteEnum(1, fieldNames[0], (int) SparseEnum); + output.WriteEnum(1, (int) SparseEnum); } } @@ -3385,16 +3259,9 @@ namespace Google.Protobuf.TestProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -3404,9 +3271,8 @@ namespace Google.Protobuf.TestProtos { } break; case 8: { - int tmp = 0; - input.ReadEnum(ref tmp); - sparseEnum_ = (global::Google.Protobuf.TestProtos.TestSparseEnum) tmp;break; + sparseEnum_ = (global::Google.Protobuf.TestProtos.TestSparseEnum) input.ReadEnum(); + break; } } } @@ -3462,10 +3328,9 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (Data != "") { - output.WriteString(1, fieldNames[0], Data); + output.WriteString(1, Data); } } @@ -3485,16 +3350,9 @@ namespace Google.Protobuf.TestProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -3504,7 +3362,7 @@ namespace Google.Protobuf.TestProtos { } break; case 10: { - input.ReadString(ref data_); + data_ = input.ReadString(); break; } } @@ -3559,9 +3417,8 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; - output.WriteStringArray(1, fieldNames[0], data_); + public void WriteTo(pb::CodedOutputStream output) { + output.WriteStringArray(1, data_); } public int CalculateSize() { @@ -3583,16 +3440,9 @@ namespace Google.Protobuf.TestProtos { data_.Add(other.data_); } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -3602,7 +3452,7 @@ namespace Google.Protobuf.TestProtos { } break; case 10: { - input.ReadStringArray(tag, fieldName, data_); + input.ReadStringArray(tag, data_); break; } } @@ -3659,10 +3509,9 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (Data != pb::ByteString.Empty) { - output.WriteBytes(1, fieldNames[0], Data); + output.WriteBytes(1, Data); } } @@ -3682,16 +3531,9 @@ namespace Google.Protobuf.TestProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -3701,7 +3543,7 @@ namespace Google.Protobuf.TestProtos { } break; case 10: { - input.ReadBytes(ref data_); + data_ = input.ReadBytes(); break; } } @@ -3758,10 +3600,9 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (Data != pb::ByteString.Empty) { - output.WriteBytes(1, fieldNames[0], Data); + output.WriteBytes(1, Data); } } @@ -3781,16 +3622,9 @@ namespace Google.Protobuf.TestProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -3800,7 +3634,7 @@ namespace Google.Protobuf.TestProtos { } break; case 10: { - input.ReadBytes(ref data_); + data_ = input.ReadBytes(); break; } } @@ -3857,10 +3691,9 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (Data != 0) { - output.WriteInt32(1, fieldNames[0], Data); + output.WriteInt32(1, Data); } } @@ -3880,16 +3713,9 @@ namespace Google.Protobuf.TestProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -3899,7 +3725,7 @@ namespace Google.Protobuf.TestProtos { } break; case 8: { - input.ReadInt32(ref data_); + data_ = input.ReadInt32(); break; } } @@ -3956,10 +3782,9 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (Data != 0) { - output.WriteUInt32(1, fieldNames[0], Data); + output.WriteUInt32(1, Data); } } @@ -3979,16 +3804,9 @@ namespace Google.Protobuf.TestProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -3998,7 +3816,7 @@ namespace Google.Protobuf.TestProtos { } break; case 8: { - input.ReadUInt32(ref data_); + data_ = input.ReadUInt32(); break; } } @@ -4055,10 +3873,9 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (Data != 0L) { - output.WriteInt64(1, fieldNames[0], Data); + output.WriteInt64(1, Data); } } @@ -4078,16 +3895,9 @@ namespace Google.Protobuf.TestProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -4097,7 +3907,7 @@ namespace Google.Protobuf.TestProtos { } break; case 8: { - input.ReadInt64(ref data_); + data_ = input.ReadInt64(); break; } } @@ -4154,10 +3964,9 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (Data != 0UL) { - output.WriteUInt64(1, fieldNames[0], Data); + output.WriteUInt64(1, Data); } } @@ -4177,16 +3986,9 @@ namespace Google.Protobuf.TestProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -4196,7 +3998,7 @@ namespace Google.Protobuf.TestProtos { } break; case 8: { - input.ReadUInt64(ref data_); + data_ = input.ReadUInt64(); break; } } @@ -4253,10 +4055,9 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (Data != false) { - output.WriteBool(1, fieldNames[0], Data); + output.WriteBool(1, Data); } } @@ -4276,16 +4077,9 @@ namespace Google.Protobuf.TestProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -4295,7 +4089,7 @@ namespace Google.Protobuf.TestProtos { } break; case 8: { - input.ReadBool(ref data_); + data_ = input.ReadBool(); break; } } @@ -4391,16 +4185,15 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (fooCase_ == FooOneofCase.FooInt) { - output.WriteInt32(1, fieldNames[0], FooInt); + output.WriteInt32(1, FooInt); } if (fooCase_ == FooOneofCase.FooString) { - output.WriteString(2, fieldNames[2], FooString); + output.WriteString(2, FooString); } if (fooCase_ == FooOneofCase.FooMessage) { - output.WriteMessage(3, fieldNames[1], FooMessage); + output.WriteMessage(3, FooMessage); } } @@ -4435,16 +4228,9 @@ namespace Google.Protobuf.TestProtos { } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -4454,19 +4240,13 @@ namespace Google.Protobuf.TestProtos { } break; case 8: { - int value = 0; - if (input.ReadInt32(ref value)) { - foo_ = value; - fooCase_ = FooOneofCase.FooInt; - } + foo_ = input.ReadInt32() + ;fooCase_ = FooOneofCase.FooInt; break; } case 18: { - string value = ""; - if (input.ReadString(ref value)) { - foo_ = value; - fooCase_ = FooOneofCase.FooString; - } + foo_ = input.ReadString() + ;fooCase_ = FooOneofCase.FooString; break; } case 26: { @@ -4634,22 +4414,21 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; - output.WritePackedInt32Array(90, fieldNames[6], packedInt32_); - output.WritePackedInt64Array(91, fieldNames[7], packedInt64_); - output.WritePackedUInt32Array(92, fieldNames[12], packedUint32_); - output.WritePackedUInt64Array(93, fieldNames[13], packedUint64_); - output.WritePackedSInt32Array(94, fieldNames[10], packedSint32_); - output.WritePackedSInt64Array(95, fieldNames[11], packedSint64_); - output.WritePackedFixed32Array(96, fieldNames[3], packedFixed32_); - output.WritePackedFixed64Array(97, fieldNames[4], packedFixed64_); - output.WritePackedSFixed32Array(98, fieldNames[8], packedSfixed32_); - output.WritePackedSFixed64Array(99, fieldNames[9], packedSfixed64_); - output.WritePackedFloatArray(100, fieldNames[5], packedFloat_); - output.WritePackedDoubleArray(101, fieldNames[1], packedDouble_); - output.WritePackedBoolArray(102, fieldNames[0], packedBool_); - output.WritePackedEnumArray(103, fieldNames[2], packedEnum_); + public void WriteTo(pb::CodedOutputStream output) { + output.WritePackedInt32Array(90, packedInt32_); + output.WritePackedInt64Array(91, packedInt64_); + output.WritePackedUInt32Array(92, packedUint32_); + output.WritePackedUInt64Array(93, packedUint64_); + output.WritePackedSInt32Array(94, packedSint32_); + output.WritePackedSInt64Array(95, packedSint64_); + output.WritePackedFixed32Array(96, packedFixed32_); + output.WritePackedFixed64Array(97, packedFixed64_); + output.WritePackedSFixed32Array(98, packedSfixed32_); + output.WritePackedSFixed64Array(99, packedSfixed64_); + output.WritePackedFloatArray(100, packedFloat_); + output.WritePackedDoubleArray(101, packedDouble_); + output.WritePackedBoolArray(102, packedBool_); + output.WritePackedEnumArray(103, packedEnum_); } public int CalculateSize() { @@ -4803,16 +4582,9 @@ namespace Google.Protobuf.TestProtos { packedEnum_.Add(other.packedEnum_); } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -4823,72 +4595,72 @@ namespace Google.Protobuf.TestProtos { break; case 722: case 720: { - input.ReadInt32Array(tag, fieldName, packedInt32_); + input.ReadInt32Array(tag, packedInt32_); break; } case 730: case 728: { - input.ReadInt64Array(tag, fieldName, packedInt64_); + input.ReadInt64Array(tag, packedInt64_); break; } case 738: case 736: { - input.ReadUInt32Array(tag, fieldName, packedUint32_); + input.ReadUInt32Array(tag, packedUint32_); break; } case 746: case 744: { - input.ReadUInt64Array(tag, fieldName, packedUint64_); + input.ReadUInt64Array(tag, packedUint64_); break; } case 754: case 752: { - input.ReadSInt32Array(tag, fieldName, packedSint32_); + input.ReadSInt32Array(tag, packedSint32_); break; } case 762: case 760: { - input.ReadSInt64Array(tag, fieldName, packedSint64_); + input.ReadSInt64Array(tag, packedSint64_); break; } case 770: case 773: { - input.ReadFixed32Array(tag, fieldName, packedFixed32_); + input.ReadFixed32Array(tag, packedFixed32_); break; } case 778: case 777: { - input.ReadFixed64Array(tag, fieldName, packedFixed64_); + input.ReadFixed64Array(tag, packedFixed64_); break; } case 786: case 789: { - input.ReadSFixed32Array(tag, fieldName, packedSfixed32_); + input.ReadSFixed32Array(tag, packedSfixed32_); break; } case 794: case 793: { - input.ReadSFixed64Array(tag, fieldName, packedSfixed64_); + input.ReadSFixed64Array(tag, packedSfixed64_); break; } case 802: case 805: { - input.ReadFloatArray(tag, fieldName, packedFloat_); + input.ReadFloatArray(tag, packedFloat_); break; } case 810: case 809: { - input.ReadDoubleArray(tag, fieldName, packedDouble_); + input.ReadDoubleArray(tag, packedDouble_); break; } case 818: case 816: { - input.ReadBoolArray(tag, fieldName, packedBool_); + input.ReadBoolArray(tag, packedBool_); break; } case 826: case 824: { - input.ReadEnumArray(tag, fieldName, packedEnum_); + input.ReadEnumArray(tag, packedEnum_); break; } } @@ -5047,22 +4819,21 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; - output.WriteInt32Array(90, fieldNames[6], unpackedInt32_); - output.WriteInt64Array(91, fieldNames[7], unpackedInt64_); - output.WriteUInt32Array(92, fieldNames[12], unpackedUint32_); - output.WriteUInt64Array(93, fieldNames[13], unpackedUint64_); - output.WriteSInt32Array(94, fieldNames[10], unpackedSint32_); - output.WriteSInt64Array(95, fieldNames[11], unpackedSint64_); - output.WriteFixed32Array(96, fieldNames[3], unpackedFixed32_); - output.WriteFixed64Array(97, fieldNames[4], unpackedFixed64_); - output.WriteSFixed32Array(98, fieldNames[8], unpackedSfixed32_); - output.WriteSFixed64Array(99, fieldNames[9], unpackedSfixed64_); - output.WriteFloatArray(100, fieldNames[5], unpackedFloat_); - output.WriteDoubleArray(101, fieldNames[1], unpackedDouble_); - output.WriteBoolArray(102, fieldNames[0], unpackedBool_); - output.WriteEnumArray(103, fieldNames[2], unpackedEnum_); + public void WriteTo(pb::CodedOutputStream output) { + output.WriteInt32Array(90, unpackedInt32_); + output.WriteInt64Array(91, unpackedInt64_); + output.WriteUInt32Array(92, unpackedUint32_); + output.WriteUInt64Array(93, unpackedUint64_); + output.WriteSInt32Array(94, unpackedSint32_); + output.WriteSInt64Array(95, unpackedSint64_); + output.WriteFixed32Array(96, unpackedFixed32_); + output.WriteFixed64Array(97, unpackedFixed64_); + output.WriteSFixed32Array(98, unpackedSfixed32_); + output.WriteSFixed64Array(99, unpackedSfixed64_); + output.WriteFloatArray(100, unpackedFloat_); + output.WriteDoubleArray(101, unpackedDouble_); + output.WriteBoolArray(102, unpackedBool_); + output.WriteEnumArray(103, unpackedEnum_); } public int CalculateSize() { @@ -5189,16 +4960,9 @@ namespace Google.Protobuf.TestProtos { unpackedEnum_.Add(other.unpackedEnum_); } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -5209,72 +4973,72 @@ namespace Google.Protobuf.TestProtos { break; case 722: case 720: { - input.ReadInt32Array(tag, fieldName, unpackedInt32_); + input.ReadInt32Array(tag, unpackedInt32_); break; } case 730: case 728: { - input.ReadInt64Array(tag, fieldName, unpackedInt64_); + input.ReadInt64Array(tag, unpackedInt64_); break; } case 738: case 736: { - input.ReadUInt32Array(tag, fieldName, unpackedUint32_); + input.ReadUInt32Array(tag, unpackedUint32_); break; } case 746: case 744: { - input.ReadUInt64Array(tag, fieldName, unpackedUint64_); + input.ReadUInt64Array(tag, unpackedUint64_); break; } case 754: case 752: { - input.ReadSInt32Array(tag, fieldName, unpackedSint32_); + input.ReadSInt32Array(tag, unpackedSint32_); break; } case 762: case 760: { - input.ReadSInt64Array(tag, fieldName, unpackedSint64_); + input.ReadSInt64Array(tag, unpackedSint64_); break; } case 770: case 773: { - input.ReadFixed32Array(tag, fieldName, unpackedFixed32_); + input.ReadFixed32Array(tag, unpackedFixed32_); break; } case 778: case 777: { - input.ReadFixed64Array(tag, fieldName, unpackedFixed64_); + input.ReadFixed64Array(tag, unpackedFixed64_); break; } case 786: case 789: { - input.ReadSFixed32Array(tag, fieldName, unpackedSfixed32_); + input.ReadSFixed32Array(tag, unpackedSfixed32_); break; } case 794: case 793: { - input.ReadSFixed64Array(tag, fieldName, unpackedSfixed64_); + input.ReadSFixed64Array(tag, unpackedSfixed64_); break; } case 802: case 805: { - input.ReadFloatArray(tag, fieldName, unpackedFloat_); + input.ReadFloatArray(tag, unpackedFloat_); break; } case 810: case 809: { - input.ReadDoubleArray(tag, fieldName, unpackedDouble_); + input.ReadDoubleArray(tag, unpackedDouble_); break; } case 818: case 816: { - input.ReadBoolArray(tag, fieldName, unpackedBool_); + input.ReadBoolArray(tag, unpackedBool_); break; } case 826: case 824: { - input.ReadEnumArray(tag, fieldName, unpackedEnum_); + input.ReadEnumArray(tag, unpackedEnum_); break; } } @@ -5369,14 +5133,13 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; - output.WritePackedFixed32Array(12, fieldNames[0], repeatedFixed32_); - output.WritePackedInt32Array(13, fieldNames[3], repeatedInt32_); - output.WritePackedFixed64Array(2046, fieldNames[1], repeatedFixed64_); - output.WritePackedInt64Array(2047, fieldNames[4], repeatedInt64_); - output.WritePackedFloatArray(262142, fieldNames[2], repeatedFloat_); - output.WritePackedUInt64Array(262143, fieldNames[5], repeatedUint64_); + public void WriteTo(pb::CodedOutputStream output) { + output.WritePackedFixed32Array(12, repeatedFixed32_); + output.WritePackedInt32Array(13, repeatedInt32_); + output.WritePackedFixed64Array(2046, repeatedFixed64_); + output.WritePackedInt64Array(2047, repeatedInt64_); + output.WritePackedFloatArray(262142, repeatedFloat_); + output.WritePackedUInt64Array(262143, repeatedUint64_); } public int CalculateSize() { @@ -5449,16 +5212,9 @@ namespace Google.Protobuf.TestProtos { repeatedUint64_.Add(other.repeatedUint64_); } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -5469,32 +5225,32 @@ namespace Google.Protobuf.TestProtos { break; case 98: case 101: { - input.ReadFixed32Array(tag, fieldName, repeatedFixed32_); + input.ReadFixed32Array(tag, repeatedFixed32_); break; } case 106: case 104: { - input.ReadInt32Array(tag, fieldName, repeatedInt32_); + input.ReadInt32Array(tag, repeatedInt32_); break; } case 16370: case 16369: { - input.ReadFixed64Array(tag, fieldName, repeatedFixed64_); + input.ReadFixed64Array(tag, repeatedFixed64_); break; } case 16378: case 16376: { - input.ReadInt64Array(tag, fieldName, repeatedInt64_); + input.ReadInt64Array(tag, repeatedInt64_); break; } case 2097138: case 2097141: { - input.ReadFloatArray(tag, fieldName, repeatedFloat_); + input.ReadFloatArray(tag, repeatedFloat_); break; } case 2097146: case 2097144: { - input.ReadUInt64Array(tag, fieldName, repeatedUint64_); + input.ReadUInt64Array(tag, repeatedUint64_); break; } } @@ -5551,10 +5307,9 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (A != "") { - output.WriteString(1, fieldNames[0], A); + output.WriteString(1, A); } } @@ -5574,16 +5329,9 @@ namespace Google.Protobuf.TestProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -5593,7 +5341,7 @@ namespace Google.Protobuf.TestProtos { } break; case 10: { - input.ReadString(ref a_); + a_ = input.ReadString(); break; } } @@ -5640,8 +5388,7 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { } public int CalculateSize() { @@ -5654,16 +5401,9 @@ namespace Google.Protobuf.TestProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -5716,8 +5456,7 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { } public int CalculateSize() { @@ -5730,16 +5469,9 @@ namespace Google.Protobuf.TestProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -5792,8 +5524,7 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { } public int CalculateSize() { @@ -5806,16 +5537,9 @@ namespace Google.Protobuf.TestProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -5868,8 +5592,7 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { } public int CalculateSize() { @@ -5882,16 +5605,9 @@ namespace Google.Protobuf.TestProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -5944,8 +5660,7 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { } public int CalculateSize() { @@ -5958,16 +5673,9 @@ namespace Google.Protobuf.TestProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -6020,8 +5728,7 @@ namespace Google.Protobuf.TestProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { } public int CalculateSize() { @@ -6034,16 +5741,9 @@ namespace Google.Protobuf.TestProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); diff --git a/csharp/src/ProtocolBuffers/CodedInputStream.cs b/csharp/src/ProtocolBuffers/CodedInputStream.cs index d5cab6fd..cb47f1c2 100644 --- a/csharp/src/ProtocolBuffers/CodedInputStream.cs +++ b/csharp/src/ProtocolBuffers/CodedInputStream.cs @@ -58,7 +58,7 @@ namespace Google.Protobuf /// TODO(jonskeet): Consider whether recursion and size limits shouldn't be readonly, /// set at construction time. /// - public sealed class CodedInputStream : ICodedInputStream + public sealed class CodedInputStream { private readonly byte[] buffer; private int bufferSize; @@ -173,10 +173,6 @@ namespace Google.Protobuf } } - - void ICodedInputStream.ReadMessageStart() { } - void ICodedInputStream.ReadMessageEnd() { } - #region Validation /// @@ -201,17 +197,16 @@ namespace Google.Protobuf /// /// Attempt to peek at the next field tag. /// - public bool PeekNextTag(out uint fieldTag, out string fieldName) + public bool PeekNextTag(out uint fieldTag) { if (hasNextTag) { - fieldName = null; fieldTag = nextTag; return true; } uint savedLast = lastTag; - hasNextTag = ReadTag(out nextTag, out fieldName); + hasNextTag = ReadTag(out nextTag); lastTag = savedLast; fieldTag = nextTag; return hasNextTag; @@ -222,12 +217,9 @@ namespace Google.Protobuf /// of the input data. /// /// The 'tag' of the field (id * 8 + wire-format) - /// Not Supported - For protobuffer streams, this parameter is always null /// true if the next fieldTag was read - public bool ReadTag(out uint fieldTag, out string fieldName) + public bool ReadTag(out uint fieldTag) { - fieldName = null; - if (hasNextTag) { fieldTag = nextTag; @@ -256,21 +248,21 @@ namespace Google.Protobuf /// /// Read a double field from the stream. /// - public bool ReadDouble(ref double value) + public double ReadDouble() { - value = FrameworkPortability.Int64ToDouble((long) ReadRawLittleEndian64()); - return true; + return FrameworkPortability.Int64ToDouble((long) ReadRawLittleEndian64()); } /// /// Read a float field from the stream. /// - public bool ReadFloat(ref float value) + public float ReadFloat() { if (BitConverter.IsLittleEndian && 4 <= bufferSize - bufferPos) { - value = BitConverter.ToSingle(buffer, bufferPos); + float ret = BitConverter.ToSingle(buffer, bufferPos); bufferPos += 4; + return ret; } else { @@ -279,76 +271,68 @@ namespace Google.Protobuf { ByteArray.Reverse(rawBytes); } - value = BitConverter.ToSingle(rawBytes, 0); + return BitConverter.ToSingle(rawBytes, 0); } - return true; } /// /// Read a uint64 field from the stream. /// - public bool ReadUInt64(ref ulong value) + public ulong ReadUInt64() { - value = ReadRawVarint64(); - return true; + return ReadRawVarint64(); } /// /// Read an int64 field from the stream. /// - public bool ReadInt64(ref long value) + public long ReadInt64() { - value = (long) ReadRawVarint64(); - return true; + return (long) ReadRawVarint64(); } /// /// Read an int32 field from the stream. /// - public bool ReadInt32(ref int value) + public int ReadInt32() { - value = (int) ReadRawVarint32(); - return true; + return (int) ReadRawVarint32(); } /// /// Read a fixed64 field from the stream. /// - public bool ReadFixed64(ref ulong value) + public ulong ReadFixed64() { - value = ReadRawLittleEndian64(); - return true; + return ReadRawLittleEndian64(); } /// /// Read a fixed32 field from the stream. /// - public bool ReadFixed32(ref uint value) + public uint ReadFixed32() { - value = ReadRawLittleEndian32(); - return true; + return ReadRawLittleEndian32(); } /// /// Read a bool field from the stream. /// - public bool ReadBool(ref bool value) + public bool ReadBool() { - value = ReadRawVarint32() != 0; - return true; + return ReadRawVarint32() != 0; } /// /// Reads a string field from the stream. /// - public bool ReadString(ref string value) + public string ReadString() { int size = (int) ReadRawVarint32(); // No need to read any data for an empty string. if (size == 0) { - value = ""; - return true; + return ""; } if (size <= bufferSize - bufferPos) { @@ -356,12 +340,10 @@ namespace Google.Protobuf // just copy directly from it. String result = Encoding.UTF8.GetString(buffer, bufferPos, size); bufferPos += size; - value = result; - return true; + return result; } // Slow path: Build a byte array first then copy it. - value = Encoding.UTF8.GetString(ReadRawBytes(size), 0, size); - return true; + return Encoding.UTF8.GetString(ReadRawBytes(size), 0, size); } /// @@ -400,7 +382,7 @@ namespace Google.Protobuf /// /// Reads a bytes field value from the stream. /// - public bool ReadBytes(ref ByteString value) + public ByteString ReadBytes() { int size = (int) ReadRawVarint32(); if (size <= bufferSize - bufferPos && size > 0) @@ -409,24 +391,21 @@ namespace Google.Protobuf // just copy directly from it. ByteString result = ByteString.CopyFrom(buffer, bufferPos, size); bufferPos += size; - value = result; - return true; + return result; } else { // Slow path: Build a byte array and attach it to a new ByteString. - value = ByteString.AttachBytes(ReadRawBytes(size)); - return true; + return ByteString.AttachBytes(ReadRawBytes(size)); } } /// /// Reads a uint32 field value from the stream. /// - public bool ReadUInt32(ref uint value) + public uint ReadUInt32() { - value = ReadRawVarint32(); - return true; + return ReadRawVarint32(); } /// @@ -434,47 +413,42 @@ namespace Google.Protobuf /// then the ref value is set and it returns true. Otherwise the unknown output /// value is set and this method returns false. /// - public bool ReadEnum(ref int value) + public int ReadEnum() { // Currently just a pass-through, but it's nice to separate it logically from WriteInt32. - value = (int) ReadRawVarint32(); - return true; + return (int) ReadRawVarint32(); } /// /// Reads an sfixed32 field value from the stream. /// - public bool ReadSFixed32(ref int value) + public int ReadSFixed32() { - value = (int) ReadRawLittleEndian32(); - return true; + return (int) ReadRawLittleEndian32(); } /// /// Reads an sfixed64 field value from the stream. /// - public bool ReadSFixed64(ref long value) + public long ReadSFixed64() { - value = (long) ReadRawLittleEndian64(); - return true; + return (long) ReadRawLittleEndian64(); } /// /// Reads an sint32 field value from the stream. /// - public bool ReadSInt32(ref int value) + public int ReadSInt32() { - value = DecodeZigZag32(ReadRawVarint32()); - return true; + return DecodeZigZag32(ReadRawVarint32()); } /// /// Reads an sint64 field value from the stream. /// - public bool ReadSInt64(ref long value) + public long ReadSInt64() { - value = DecodeZigZag64(ReadRawVarint64()); - return true; + return DecodeZigZag64(ReadRawVarint64()); } private bool BeginArray(uint fieldTag, out bool isPacked, out int oldLimit) @@ -502,9 +476,8 @@ namespace Google.Protobuf /// private bool ContinueArray(uint currentTag) { - string ignore; uint next; - if (PeekNextTag(out next, out ignore)) + if (PeekNextTag(out next)) { if (next == currentTag) { @@ -530,9 +503,8 @@ namespace Google.Protobuf return true; } - string ignore; uint next; - if (PeekNextTag(out next, out ignore)) + if (PeekNextTag(out next)) { if (next == currentTag) { @@ -543,259 +515,194 @@ namespace Google.Protobuf return false; } - public void ReadPrimitiveArray(FieldType fieldType, uint fieldTag, string fieldName, ICollection list) - { - WireFormat.WireType normal = WireFormat.GetWireType(fieldType); - WireFormat.WireType wformat = WireFormat.GetTagWireType(fieldTag); - - // 2.3 allows packed form even if the field is not declared packed. - if (normal != wformat && wformat == WireFormat.WireType.LengthDelimited) - { - int length = (int) (ReadRawVarint32() & int.MaxValue); - int limit = PushLimit(length); - while (!ReachedLimit) - { - Object value = null; - if (ReadPrimitiveField(fieldType, ref value)) - { - list.Add(value); - } - } - PopLimit(limit); - } - else - { - Object value = null; - do - { - if (ReadPrimitiveField(fieldType, ref value)) - { - list.Add(value); - } - } while (ContinueArray(fieldTag)); - } - } - - public void ReadStringArray(uint fieldTag, string fieldName, ICollection list) + public void ReadStringArray(uint fieldTag, ICollection list) { - string tmp = null; do { - ReadString(ref tmp); - list.Add(tmp); + list.Add(ReadString()); } while (ContinueArray(fieldTag)); } - public void ReadBytesArray(uint fieldTag, string fieldName, ICollection list) + public void ReadBytesArray(uint fieldTag, ICollection list) { - ByteString tmp = null; do { - ReadBytes(ref tmp); - list.Add(tmp); + list.Add(ReadBytes()); } while (ContinueArray(fieldTag)); } - public void ReadBoolArray(uint fieldTag, string fieldName, ICollection list) + public void ReadBoolArray(uint fieldTag, ICollection list) { bool isPacked; int holdLimit; if (BeginArray(fieldTag, out isPacked, out holdLimit)) { - bool tmp = false; do { - ReadBool(ref tmp); - list.Add(tmp); + list.Add(ReadBool()); } while (ContinueArray(fieldTag, isPacked, holdLimit)); } } - public void ReadInt32Array(uint fieldTag, string fieldName, ICollection list) + public void ReadInt32Array(uint fieldTag, ICollection list) { - // TODO(jonskeet): Work out how this works for non-packed values. (It doesn't look like it does...) bool isPacked; int holdLimit; if (BeginArray(fieldTag, out isPacked, out holdLimit)) { - int tmp = 0; do { - ReadInt32(ref tmp); - list.Add(tmp); + list.Add(ReadInt32()); } while (ContinueArray(fieldTag, isPacked, holdLimit)); } } - public void ReadSInt32Array(uint fieldTag, string fieldName, ICollection list) + public void ReadSInt32Array(uint fieldTag, ICollection list) { bool isPacked; int holdLimit; if (BeginArray(fieldTag, out isPacked, out holdLimit)) { - int tmp = 0; do { - ReadSInt32(ref tmp); - list.Add(tmp); + list.Add(ReadSInt32()); } while (ContinueArray(fieldTag, isPacked, holdLimit)); } } - public void ReadUInt32Array(uint fieldTag, string fieldName, ICollection list) + public void ReadUInt32Array(uint fieldTag, ICollection list) { bool isPacked; int holdLimit; if (BeginArray(fieldTag, out isPacked, out holdLimit)) { - uint tmp = 0; do { - ReadUInt32(ref tmp); - list.Add(tmp); + list.Add(ReadUInt32()); } while (ContinueArray(fieldTag, isPacked, holdLimit)); } } - public void ReadFixed32Array(uint fieldTag, string fieldName, ICollection list) + public void ReadFixed32Array(uint fieldTag, ICollection list) { bool isPacked; int holdLimit; if (BeginArray(fieldTag, out isPacked, out holdLimit)) { - uint tmp = 0; do { - ReadFixed32(ref tmp); - list.Add(tmp); + list.Add(ReadFixed32()); } while (ContinueArray(fieldTag, isPacked, holdLimit)); } } - public void ReadSFixed32Array(uint fieldTag, string fieldName, ICollection list) + public void ReadSFixed32Array(uint fieldTag, ICollection list) { bool isPacked; int holdLimit; if (BeginArray(fieldTag, out isPacked, out holdLimit)) { - int tmp = 0; do { - ReadSFixed32(ref tmp); - list.Add(tmp); + list.Add(ReadSFixed32()); } while (ContinueArray(fieldTag, isPacked, holdLimit)); } } - public void ReadInt64Array(uint fieldTag, string fieldName, ICollection list) + public void ReadInt64Array(uint fieldTag, ICollection list) { bool isPacked; int holdLimit; if (BeginArray(fieldTag, out isPacked, out holdLimit)) { - long tmp = 0; do { - ReadInt64(ref tmp); - list.Add(tmp); + list.Add(ReadInt64()); } while (ContinueArray(fieldTag, isPacked, holdLimit)); } } - public void ReadSInt64Array(uint fieldTag, string fieldName, ICollection list) + public void ReadSInt64Array(uint fieldTag, ICollection list) { bool isPacked; int holdLimit; if (BeginArray(fieldTag, out isPacked, out holdLimit)) { - long tmp = 0; do { - ReadSInt64(ref tmp); - list.Add(tmp); + list.Add(ReadSInt64()); } while (ContinueArray(fieldTag, isPacked, holdLimit)); } } - public void ReadUInt64Array(uint fieldTag, string fieldName, ICollection list) + public void ReadUInt64Array(uint fieldTag, ICollection list) { bool isPacked; int holdLimit; if (BeginArray(fieldTag, out isPacked, out holdLimit)) { - ulong tmp = 0; do { - ReadUInt64(ref tmp); - list.Add(tmp); + list.Add(ReadUInt64()); } while (ContinueArray(fieldTag, isPacked, holdLimit)); } } - public void ReadFixed64Array(uint fieldTag, string fieldName, ICollection list) + public void ReadFixed64Array(uint fieldTag, ICollection list) { bool isPacked; int holdLimit; if (BeginArray(fieldTag, out isPacked, out holdLimit)) { - ulong tmp = 0; do { - ReadFixed64(ref tmp); - list.Add(tmp); + list.Add(ReadFixed64()); } while (ContinueArray(fieldTag, isPacked, holdLimit)); } } - public void ReadSFixed64Array(uint fieldTag, string fieldName, ICollection list) + public void ReadSFixed64Array(uint fieldTag, ICollection list) { bool isPacked; int holdLimit; if (BeginArray(fieldTag, out isPacked, out holdLimit)) { - long tmp = 0; do { - ReadSFixed64(ref tmp); - list.Add(tmp); + list.Add(ReadSFixed64()); } while (ContinueArray(fieldTag, isPacked, holdLimit)); } } - public void ReadDoubleArray(uint fieldTag, string fieldName, ICollection list) + public void ReadDoubleArray(uint fieldTag, ICollection list) { bool isPacked; int holdLimit; if (BeginArray(fieldTag, out isPacked, out holdLimit)) { - double tmp = 0; do { - ReadDouble(ref tmp); - list.Add(tmp); + list.Add(ReadDouble()); } while (ContinueArray(fieldTag, isPacked, holdLimit)); } } - public void ReadFloatArray(uint fieldTag, string fieldName, ICollection list) + public void ReadFloatArray(uint fieldTag, ICollection list) { bool isPacked; int holdLimit; if (BeginArray(fieldTag, out isPacked, out holdLimit)) { - float tmp = 0; do { - ReadFloat(ref tmp); - list.Add(tmp); + list.Add(ReadFloat()); } while (ContinueArray(fieldTag, isPacked, holdLimit)); } } - public void ReadEnumArray(uint fieldTag, string fieldName, ICollection list) + public void ReadEnumArray(uint fieldTag, ICollection list) where T : struct, IComparable, IFormattable { - int value = 0; WireFormat.WireType wformat = WireFormat.GetTagWireType(fieldTag); // 2.3 allows packed form even if the field is not declared packed. @@ -805,9 +712,8 @@ namespace Google.Protobuf int limit = PushLimit(length); while (!ReachedLimit) { - ReadEnum(ref value); // TODO(jonskeet): Avoid this horrible boxing! - list.Add((T)(object)value); + list.Add((T)(object) ReadEnum()); } PopLimit(limit); } @@ -815,14 +721,12 @@ namespace Google.Protobuf { do { - ReadEnum(ref value); - // TODO(jonskeet): Avoid this horrible boxing! - list.Add((T)(object) value); + list.Add((T)(object) ReadEnum()); } while (ContinueArray(fieldTag)); } } - public void ReadMessageArray(uint fieldTag, string fieldName, ICollection list, MessageParser messageParser) + public void ReadMessageArray(uint fieldTag, ICollection list, MessageParser messageParser) where T : IMessage { do @@ -833,7 +737,7 @@ namespace Google.Protobuf } while (ContinueArray(fieldTag)); } - public void ReadGroupArray(uint fieldTag, string fieldName, ICollection list, MessageParser messageParser) + public void ReadGroupArray(uint fieldTag, ICollection list, MessageParser messageParser) where T : IMessage { do @@ -843,178 +747,6 @@ namespace Google.Protobuf list.Add(message); } while (ContinueArray(fieldTag)); } - - /// - /// Reads a field of any primitive type. Enums, groups and embedded - /// messages are not handled by this method. - /// - public bool ReadPrimitiveField(FieldType fieldType, ref object value) - { - switch (fieldType) - { - case FieldType.Double: - { - double tmp = 0; - if (ReadDouble(ref tmp)) - { - value = tmp; - return true; - } - return false; - } - case FieldType.Float: - { - float tmp = 0; - if (ReadFloat(ref tmp)) - { - value = tmp; - return true; - } - return false; - } - case FieldType.Int64: - { - long tmp = 0; - if (ReadInt64(ref tmp)) - { - value = tmp; - return true; - } - return false; - } - case FieldType.UInt64: - { - ulong tmp = 0; - if (ReadUInt64(ref tmp)) - { - value = tmp; - return true; - } - return false; - } - case FieldType.Int32: - { - int tmp = 0; - if (ReadInt32(ref tmp)) - { - value = tmp; - return true; - } - return false; - } - case FieldType.Fixed64: - { - ulong tmp = 0; - if (ReadFixed64(ref tmp)) - { - value = tmp; - return true; - } - return false; - } - case FieldType.Fixed32: - { - uint tmp = 0; - if (ReadFixed32(ref tmp)) - { - value = tmp; - return true; - } - return false; - } - case FieldType.Bool: - { - bool tmp = false; - if (ReadBool(ref tmp)) - { - value = tmp; - return true; - } - return false; - } - case FieldType.String: - { - string tmp = null; - if (ReadString(ref tmp)) - { - value = tmp; - return true; - } - return false; - } - case FieldType.Bytes: - { - ByteString tmp = null; - if (ReadBytes(ref tmp)) - { - value = tmp; - return true; - } - return false; - } - case FieldType.UInt32: - { - uint tmp = 0; - if (ReadUInt32(ref tmp)) - { - value = tmp; - return true; - } - return false; - } - case FieldType.SFixed32: - { - int tmp = 0; - if (ReadSFixed32(ref tmp)) - { - value = tmp; - return true; - } - return false; - } - case FieldType.SFixed64: - { - long tmp = 0; - if (ReadSFixed64(ref tmp)) - { - value = tmp; - return true; - } - return false; - } - case FieldType.SInt32: - { - int tmp = 0; - if (ReadSInt32(ref tmp)) - { - value = tmp; - return true; - } - return false; - } - case FieldType.SInt64: - { - long tmp = 0; - if (ReadSInt64(ref tmp)) - { - value = tmp; - return true; - } - return false; - } - case FieldType.Group: - throw new ArgumentException("ReadPrimitiveField() cannot handle nested groups."); - case FieldType.Message: - throw new ArgumentException("ReadPrimitiveField() cannot handle embedded messages."); - // We don't handle enums because we don't know what to do if the - // value is not recognized. - case FieldType.Enum: - throw new ArgumentException("ReadPrimitiveField() cannot handle enums."); - default: - throw new ArgumentOutOfRangeException("Invalid field type " + fieldType); - } - } - #endregion #region Underlying reading primitives @@ -1622,8 +1354,7 @@ namespace Google.Protobuf public void SkipMessage() { uint tag; - string name; - while (ReadTag(out tag, out name)) + while (ReadTag(out tag)) { if (!SkipField()) { diff --git a/csharp/src/ProtocolBuffers/CodedOutputStream.ComputeSize.cs b/csharp/src/ProtocolBuffers/CodedOutputStream.ComputeSize.cs index 96be9db5..b7629d7c 100644 --- a/csharp/src/ProtocolBuffers/CodedOutputStream.ComputeSize.cs +++ b/csharp/src/ProtocolBuffers/CodedOutputStream.ComputeSize.cs @@ -413,41 +413,12 @@ namespace Google.Protobuf return ComputeRawVarint64Size(EncodeZigZag64(value)); } - /* - * Compute the number of bytes that would be needed to encode a - * MessageSet extension to the stream. For historical reasons, - * the wire format differs from normal fields. - */ - - /// - /// Compute the number of bytes that would be needed to encode a - /// MessageSet extension to the stream. For historical reasons, - /// the wire format differs from normal fields. - /// - public static int ComputeMessageSetExtensionSize(int fieldNumber, IMessage value) - { - return ComputeTagSize(WireFormat.MessageSetField.Item)*2 + - ComputeUInt32Size(WireFormat.MessageSetField.TypeID, (uint) fieldNumber) + - ComputeMessageSize(WireFormat.MessageSetField.Message, value); - } - - /// - /// Compute the number of bytes that would be needed to encode an - /// unparsed MessageSet extension field to the stream. For - /// historical reasons, the wire format differs from normal fields. - /// - public static int ComputeRawMessageSetExtensionSize(int fieldNumber, ByteString value) - { - return ComputeTagSize(WireFormat.MessageSetField.Item)*2 + - ComputeUInt32Size(WireFormat.MessageSetField.TypeID, (uint) fieldNumber) + - ComputeBytesSize(WireFormat.MessageSetField.Message, value); - } - /// /// Compute the number of bytes that would be needed to encode a varint. /// public static int ComputeRawVarint32Size(uint value) { + // TODO(jonskeet): Look at optimizing this to just hard-coded comparisons. if ((value & (0xffffffff << 7)) == 0) { return 1; @@ -472,6 +443,7 @@ namespace Google.Protobuf /// public static int ComputeRawVarint64Size(ulong value) { + // TODO(jonskeet): Look at optimizing this to just hard-coded comparisons. if ((value & (0xffffffffffffffffL << 7)) == 0) { return 1; @@ -511,106 +483,6 @@ namespace Google.Protobuf return 10; } - /// - /// Compute the number of bytes that would be needed to encode a - /// field of arbitrary type, including the tag, to the stream. - /// - // TODO(jonskeet): Why do we need this? - public static int ComputeFieldSize(FieldType fieldType, int fieldNumber, Object value) - { - switch (fieldType) - { - case FieldType.Double: - return ComputeDoubleSize(fieldNumber, (double) value); - case FieldType.Float: - return ComputeFloatSize(fieldNumber, (float) value); - case FieldType.Int64: - return ComputeInt64Size(fieldNumber, (long) value); - case FieldType.UInt64: - return ComputeUInt64Size(fieldNumber, (ulong) value); - case FieldType.Int32: - return ComputeInt32Size(fieldNumber, (int) value); - case FieldType.Fixed64: - return ComputeFixed64Size(fieldNumber, (ulong) value); - case FieldType.Fixed32: - return ComputeFixed32Size(fieldNumber, (uint) value); - case FieldType.Bool: - return ComputeBoolSize(fieldNumber, (bool) value); - case FieldType.String: - return ComputeStringSize(fieldNumber, (string) value); - case FieldType.Group: - return ComputeGroupSize(fieldNumber, (IMessage) value); - case FieldType.Message: - return ComputeMessageSize(fieldNumber, (IMessage) value); - case FieldType.Bytes: - return ComputeBytesSize(fieldNumber, (ByteString) value); - case FieldType.UInt32: - return ComputeUInt32Size(fieldNumber, (uint) value); - case FieldType.SFixed32: - return ComputeSFixed32Size(fieldNumber, (int) value); - case FieldType.SFixed64: - return ComputeSFixed64Size(fieldNumber, (long) value); - case FieldType.SInt32: - return ComputeSInt32Size(fieldNumber, (int) value); - case FieldType.SInt64: - return ComputeSInt64Size(fieldNumber, (long) value); - case FieldType.Enum: - return ComputeEnumSize(fieldNumber, (int) value); - default: - throw new ArgumentOutOfRangeException("Invalid field type " + fieldType); - } - } - - /// - /// Compute the number of bytes that would be needed to encode a - /// field of arbitrary type, excluding the tag, to the stream. - /// - // TODO(jonskeet): Why do we need this? - public static int ComputeFieldSizeNoTag(FieldType fieldType, Object value) - { - switch (fieldType) - { - case FieldType.Double: - return ComputeDoubleSizeNoTag((double) value); - case FieldType.Float: - return ComputeFloatSizeNoTag((float) value); - case FieldType.Int64: - return ComputeInt64SizeNoTag((long) value); - case FieldType.UInt64: - return ComputeUInt64SizeNoTag((ulong) value); - case FieldType.Int32: - return ComputeInt32SizeNoTag((int) value); - case FieldType.Fixed64: - return ComputeFixed64SizeNoTag((ulong) value); - case FieldType.Fixed32: - return ComputeFixed32SizeNoTag((uint) value); - case FieldType.Bool: - return ComputeBoolSizeNoTag((bool) value); - case FieldType.String: - return ComputeStringSizeNoTag((string) value); - case FieldType.Group: - return ComputeGroupSizeNoTag((IMessage) value); - case FieldType.Message: - return ComputeMessageSizeNoTag((IMessage) value); - case FieldType.Bytes: - return ComputeBytesSizeNoTag((ByteString) value); - case FieldType.UInt32: - return ComputeUInt32SizeNoTag((uint) value); - case FieldType.SFixed32: - return ComputeSFixed32SizeNoTag((int) value); - case FieldType.SFixed64: - return ComputeSFixed64SizeNoTag((long) value); - case FieldType.SInt32: - return ComputeSInt32SizeNoTag((int) value); - case FieldType.SInt64: - return ComputeSInt64SizeNoTag((long) value); - case FieldType.Enum: - return ComputeEnumSizeNoTag((int) value); - default: - throw new ArgumentOutOfRangeException("Invalid field type " + fieldType); - } - } - /// /// Compute the number of bytes that would be needed to encode a tag. /// diff --git a/csharp/src/ProtocolBuffers/CodedOutputStream.cs b/csharp/src/ProtocolBuffers/CodedOutputStream.cs index e3f0c700..132f8067 100644 --- a/csharp/src/ProtocolBuffers/CodedOutputStream.cs +++ b/csharp/src/ProtocolBuffers/CodedOutputStream.cs @@ -57,7 +57,7 @@ namespace Google.Protobuf /// methods are taken from the protocol buffer type names, not .NET types. /// (Hence WriteFloat instead of WriteSingle, and WriteBool instead of WriteBoolean.) /// - public sealed partial class CodedOutputStream : ICodedOutputStream + public sealed partial class CodedOutputStream { private static readonly Encoding UTF8 = Encoding.UTF8; @@ -143,76 +143,11 @@ namespace Google.Protobuf } } - void ICodedOutputStream.WriteMessageStart() { } - void ICodedOutputStream.WriteMessageEnd() { Flush(); } - #region Writing of tags and fields - - // TODO(jonskeet): Do we need this? - public void WriteField(FieldType fieldType, int fieldNumber, string fieldName, object value) - { - switch (fieldType) - { - case FieldType.String: - WriteString(fieldNumber, fieldName, (string) value); - break; - case FieldType.Message: - WriteMessage(fieldNumber, fieldName, (IMessage) value); - break; - case FieldType.Group: - WriteGroup(fieldNumber, fieldName, (IMessage) value); - break; - case FieldType.Bytes: - WriteBytes(fieldNumber, fieldName, (ByteString) value); - break; - case FieldType.Bool: - WriteBool(fieldNumber, fieldName, (bool) value); - break; - case FieldType.Enum: - throw new NotImplementedException(); - case FieldType.Int32: - WriteInt32(fieldNumber, fieldName, (int) value); - break; - case FieldType.Int64: - WriteInt64(fieldNumber, fieldName, (long) value); - break; - case FieldType.UInt32: - WriteUInt32(fieldNumber, fieldName, (uint) value); - break; - case FieldType.UInt64: - WriteUInt64(fieldNumber, fieldName, (ulong) value); - break; - case FieldType.SInt32: - WriteSInt32(fieldNumber, fieldName, (int) value); - break; - case FieldType.SInt64: - WriteSInt64(fieldNumber, fieldName, (long) value); - break; - case FieldType.Fixed32: - WriteFixed32(fieldNumber, fieldName, (uint) value); - break; - case FieldType.Fixed64: - WriteFixed64(fieldNumber, fieldName, (ulong) value); - break; - case FieldType.SFixed32: - WriteSFixed32(fieldNumber, fieldName, (int) value); - break; - case FieldType.SFixed64: - WriteSFixed64(fieldNumber, fieldName, (long) value); - break; - case FieldType.Double: - WriteDouble(fieldNumber, fieldName, (double) value); - break; - case FieldType.Float: - WriteFloat(fieldNumber, fieldName, (float) value); - break; - } - } - /// /// Writes a double field value, including tag, to the stream. /// - public void WriteDouble(int fieldNumber, string fieldName, double value) + public void WriteDouble(int fieldNumber, double value) { WriteTag(fieldNumber, WireFormat.WireType.Fixed64); WriteDoubleNoTag(value); @@ -221,7 +156,7 @@ namespace Google.Protobuf /// /// Writes a float field value, including tag, to the stream. /// - public void WriteFloat(int fieldNumber, string fieldName, float value) + public void WriteFloat(int fieldNumber, float value) { WriteTag(fieldNumber, WireFormat.WireType.Fixed32); WriteFloatNoTag(value); @@ -230,7 +165,7 @@ namespace Google.Protobuf /// /// Writes a uint64 field value, including tag, to the stream. /// - public void WriteUInt64(int fieldNumber, string fieldName, ulong value) + public void WriteUInt64(int fieldNumber, ulong value) { WriteTag(fieldNumber, WireFormat.WireType.Varint); WriteRawVarint64(value); @@ -239,7 +174,7 @@ namespace Google.Protobuf /// /// Writes an int64 field value, including tag, to the stream. /// - public void WriteInt64(int fieldNumber, string fieldName, long value) + public void WriteInt64(int fieldNumber, long value) { WriteTag(fieldNumber, WireFormat.WireType.Varint); WriteRawVarint64((ulong) value); @@ -248,7 +183,7 @@ namespace Google.Protobuf /// /// Writes an int32 field value, including tag, to the stream. /// - public void WriteInt32(int fieldNumber, string fieldName, int value) + public void WriteInt32(int fieldNumber, int value) { WriteTag(fieldNumber, WireFormat.WireType.Varint); if (value >= 0) @@ -265,7 +200,7 @@ namespace Google.Protobuf /// /// Writes a fixed64 field value, including tag, to the stream. /// - public void WriteFixed64(int fieldNumber, string fieldName, ulong value) + public void WriteFixed64(int fieldNumber, ulong value) { WriteTag(fieldNumber, WireFormat.WireType.Fixed64); WriteRawLittleEndian64(value); @@ -274,7 +209,7 @@ namespace Google.Protobuf /// /// Writes a fixed32 field value, including tag, to the stream. /// - public void WriteFixed32(int fieldNumber, string fieldName, uint value) + public void WriteFixed32(int fieldNumber, uint value) { WriteTag(fieldNumber, WireFormat.WireType.Fixed32); WriteRawLittleEndian32(value); @@ -283,7 +218,7 @@ namespace Google.Protobuf /// /// Writes a bool field value, including tag, to the stream. /// - public void WriteBool(int fieldNumber, string fieldName, bool value) + public void WriteBool(int fieldNumber, bool value) { WriteTag(fieldNumber, WireFormat.WireType.Varint); WriteRawByte(value ? (byte) 1 : (byte) 0); @@ -292,7 +227,7 @@ namespace Google.Protobuf /// /// Writes a string field value, including tag, to the stream. /// - public void WriteString(int fieldNumber, string fieldName, string value) + public void WriteString(int fieldNumber, string value) { WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited); // Optimise the case where we have enough space to write @@ -324,80 +259,63 @@ namespace Google.Protobuf /// /// Writes a group field value, including tag, to the stream. /// - public void WriteGroup(int fieldNumber, string fieldName, IMessage value) + public void WriteGroup(int fieldNumber, IMessage value) { WriteTag(fieldNumber, WireFormat.WireType.StartGroup); value.WriteTo(this); WriteTag(fieldNumber, WireFormat.WireType.EndGroup); } - public void WriteMessage(int fieldNumber, string fieldName, IMessage value) + public void WriteMessage(int fieldNumber, IMessage value) { WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited); WriteRawVarint32((uint) value.CalculateSize()); value.WriteTo(this); } - public void WriteBytes(int fieldNumber, string fieldName, ByteString value) + public void WriteBytes(int fieldNumber, ByteString value) { WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited); WriteRawVarint32((uint) value.Length); value.WriteRawBytesTo(this); } - public void WriteUInt32(int fieldNumber, string fieldName, uint value) + public void WriteUInt32(int fieldNumber, uint value) { WriteTag(fieldNumber, WireFormat.WireType.Varint); WriteRawVarint32(value); } - public void WriteEnum(int fieldNumber, string fieldName, int value) + public void WriteEnum(int fieldNumber, int value) { // Currently just a pass-through, but it's nice to separate it logically from WriteInt32. WriteTag(fieldNumber, WireFormat.WireType.Varint); WriteInt32NoTag(value); } - public void WriteSFixed32(int fieldNumber, string fieldName, int value) + public void WriteSFixed32(int fieldNumber, int value) { WriteTag(fieldNumber, WireFormat.WireType.Fixed32); WriteRawLittleEndian32((uint) value); } - public void WriteSFixed64(int fieldNumber, string fieldName, long value) + public void WriteSFixed64(int fieldNumber, long value) { WriteTag(fieldNumber, WireFormat.WireType.Fixed64); WriteRawLittleEndian64((ulong) value); } - public void WriteSInt32(int fieldNumber, string fieldName, int value) + public void WriteSInt32(int fieldNumber, int value) { WriteTag(fieldNumber, WireFormat.WireType.Varint); WriteRawVarint32(EncodeZigZag32(value)); } - public void WriteSInt64(int fieldNumber, string fieldName, long value) + public void WriteSInt64(int fieldNumber, long value) { WriteTag(fieldNumber, WireFormat.WireType.Varint); WriteRawVarint64(EncodeZigZag64(value)); } - - public void WriteMessageSetExtension(int fieldNumber, string fieldName, IMessage value) - { - WriteTag(WireFormat.MessageSetField.Item, WireFormat.WireType.StartGroup); - WriteUInt32(WireFormat.MessageSetField.TypeID, "type_id", (uint) fieldNumber); - WriteMessage(WireFormat.MessageSetField.Message, "message", value); - WriteTag(WireFormat.MessageSetField.Item, WireFormat.WireType.EndGroup); - } - - public void WriteMessageSetExtension(int fieldNumber, string fieldName, ByteString value) - { - WriteTag(WireFormat.MessageSetField.Item, WireFormat.WireType.StartGroup); - WriteUInt32(WireFormat.MessageSetField.TypeID, "type_id", (uint) fieldNumber); - WriteBytes(WireFormat.MessageSetField.Message, "message", value); - WriteTag(WireFormat.MessageSetField.Item, WireFormat.WireType.EndGroup); - } - #endregion #region Writing of values without tags @@ -625,155 +543,145 @@ namespace Google.Protobuf #endregion #region Write array members - - // TODO(jonskeet): Remove? - public void WriteArray(FieldType fieldType, int fieldNumber, string fieldName, IEnumerable list) - { - foreach (object element in list) - { - WriteField(fieldType, fieldNumber, fieldName, element); - } - } - - public void WriteGroupArray(int fieldNumber, string fieldName, RepeatedField list) + public void WriteGroupArray(int fieldNumber, RepeatedField list) where T : IMessage { foreach (IMessage value in list) { - WriteGroup(fieldNumber, fieldName, value); + WriteGroup(fieldNumber, value); } } - public void WriteMessageArray(int fieldNumber, string fieldName, RepeatedField list) + public void WriteMessageArray(int fieldNumber, RepeatedField list) where T : IMessage { foreach (IMessage value in list) { - WriteMessage(fieldNumber, fieldName, value); + WriteMessage(fieldNumber, value); } } - public void WriteStringArray(int fieldNumber, string fieldName, RepeatedField list) + public void WriteStringArray(int fieldNumber, RepeatedField list) { foreach (var value in list) { - WriteString(fieldNumber, fieldName, value); + WriteString(fieldNumber, value); } } - public void WriteBytesArray(int fieldNumber, string fieldName, RepeatedField list) + public void WriteBytesArray(int fieldNumber, RepeatedField list) { foreach (var value in list) { - WriteBytes(fieldNumber, fieldName, value); + WriteBytes(fieldNumber, value); } } - public void WriteBoolArray(int fieldNumber, string fieldName, RepeatedField list) + public void WriteBoolArray(int fieldNumber, RepeatedField list) { foreach (var value in list) { - WriteBool(fieldNumber, fieldName, value); + WriteBool(fieldNumber, value); } } - public void WriteInt32Array(int fieldNumber, string fieldName, RepeatedField list) + public void WriteInt32Array(int fieldNumber, RepeatedField list) { foreach (var value in list) { - WriteInt32(fieldNumber, fieldName, value); + WriteInt32(fieldNumber, value); } } - public void WriteSInt32Array(int fieldNumber, string fieldName, RepeatedField list) + public void WriteSInt32Array(int fieldNumber, RepeatedField list) { foreach (var value in list) { - WriteSInt32(fieldNumber, fieldName, value); + WriteSInt32(fieldNumber, value); } } - public void WriteUInt32Array(int fieldNumber, string fieldName, RepeatedField list) + public void WriteUInt32Array(int fieldNumber, RepeatedField list) { foreach (var value in list) { - WriteUInt32(fieldNumber, fieldName, value); + WriteUInt32(fieldNumber, value); } } - public void WriteFixed32Array(int fieldNumber, string fieldName, RepeatedField list) + public void WriteFixed32Array(int fieldNumber, RepeatedField list) { foreach (var value in list) { - WriteFixed32(fieldNumber, fieldName, value); + WriteFixed32(fieldNumber, value); } } - public void WriteSFixed32Array(int fieldNumber, string fieldName, RepeatedField list) + public void WriteSFixed32Array(int fieldNumber, RepeatedField list) { foreach (var value in list) { - WriteSFixed32(fieldNumber, fieldName, value); + WriteSFixed32(fieldNumber, value); } } - public void WriteInt64Array(int fieldNumber, string fieldName, RepeatedField list) + public void WriteInt64Array(int fieldNumber, RepeatedField list) { foreach (var value in list) { - WriteInt64(fieldNumber, fieldName, value); + WriteInt64(fieldNumber, value); } } - public void WriteSInt64Array(int fieldNumber, string fieldName, RepeatedField list) + public void WriteSInt64Array(int fieldNumber, RepeatedField list) { foreach (var value in list) { - WriteSInt64(fieldNumber, fieldName, value); + WriteSInt64(fieldNumber, value); } } - public void WriteUInt64Array(int fieldNumber, string fieldName, RepeatedField list) + public void WriteUInt64Array(int fieldNumber, RepeatedField list) { foreach (var value in list) { - WriteUInt64(fieldNumber, fieldName, value); + WriteUInt64(fieldNumber, value); } } - public void WriteFixed64Array(int fieldNumber, string fieldName, RepeatedField list) + public void WriteFixed64Array(int fieldNumber, RepeatedField list) { foreach (var value in list) { - WriteFixed64(fieldNumber, fieldName, value); + WriteFixed64(fieldNumber, value); } } - public void WriteSFixed64Array(int fieldNumber, string fieldName, RepeatedField list) + public void WriteSFixed64Array(int fieldNumber, RepeatedField list) { foreach (var value in list) { - WriteSFixed64(fieldNumber, fieldName, value); + WriteSFixed64(fieldNumber, value); } } - public void WriteDoubleArray(int fieldNumber, string fieldName, RepeatedField list) + public void WriteDoubleArray(int fieldNumber, RepeatedField list) { foreach (var value in list) { - WriteDouble(fieldNumber, fieldName, value); + WriteDouble(fieldNumber, value); } } - public void WriteFloatArray(int fieldNumber, string fieldName, RepeatedField list) + public void WriteFloatArray(int fieldNumber, RepeatedField list) { foreach (var value in list) { - WriteFloat(fieldNumber, fieldName, value); + WriteFloat(fieldNumber, value); } } - public void WriteEnumArray(int fieldNumber, string fieldName, RepeatedField list) + public void WriteEnumArray(int fieldNumber, RepeatedField list) where T : struct, IComparable, IFormattable { if (list.Count == 0) @@ -783,34 +691,15 @@ namespace Google.Protobuf // TODO(jonskeet): Avoid the Cast call here. Work out a better mass "T to int" conversion. foreach (int value in list.Cast()) { - WriteEnum(fieldNumber, fieldName, value); + WriteEnum(fieldNumber, value); } } #endregion #region Write packed array members - - // TODO(jonskeet): Remove? - public void WritePackedArray(FieldType fieldType, int fieldNumber, string fieldName, IEnumerable list) - { - int calculatedSize = 0; - foreach (object element in list) - { - calculatedSize += ComputeFieldSizeNoTag(fieldType, element); - } - - WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited); - WriteRawVarint32((uint) calculatedSize); - - foreach (object element in list) - { - WriteFieldNoTag(fieldType, element); - } - } - // TODO(jonskeet): A lot of these are really inefficient, due to method group conversions. Fix! - public void WritePackedBoolArray(int fieldNumber, string fieldName, RepeatedField list) + public void WritePackedBoolArray(int fieldNumber, RepeatedField list) { if (list.Count == 0) { @@ -825,7 +714,7 @@ namespace Google.Protobuf } } - public void WritePackedInt32Array(int fieldNumber, string fieldName, RepeatedField list) + public void WritePackedInt32Array(int fieldNumber, RepeatedField list) { if (list.Count == 0) { @@ -840,7 +729,7 @@ namespace Google.Protobuf } } - public void WritePackedSInt32Array(int fieldNumber, string fieldName, RepeatedField list) + public void WritePackedSInt32Array(int fieldNumber, RepeatedField list) { if (list.Count == 0) { @@ -855,7 +744,7 @@ namespace Google.Protobuf } } - public void WritePackedUInt32Array(int fieldNumber, string fieldName, RepeatedField list) + public void WritePackedUInt32Array(int fieldNumber, RepeatedField list) { if (list.Count == 0) { @@ -870,7 +759,7 @@ namespace Google.Protobuf } } - public void WritePackedFixed32Array(int fieldNumber, string fieldName, RepeatedField list) + public void WritePackedFixed32Array(int fieldNumber, RepeatedField list) { if (list.Count == 0) { @@ -885,7 +774,7 @@ namespace Google.Protobuf } } - public void WritePackedSFixed32Array(int fieldNumber, string fieldName, RepeatedField list) + public void WritePackedSFixed32Array(int fieldNumber, RepeatedField list) { if (list.Count == 0) { @@ -900,7 +789,7 @@ namespace Google.Protobuf } } - public void WritePackedInt64Array(int fieldNumber, string fieldName, RepeatedField list) + public void WritePackedInt64Array(int fieldNumber, RepeatedField list) { if (list.Count == 0) { @@ -915,7 +804,7 @@ namespace Google.Protobuf } } - public void WritePackedSInt64Array(int fieldNumber, string fieldName, RepeatedField list) + public void WritePackedSInt64Array(int fieldNumber, RepeatedField list) { if (list.Count == 0) { @@ -930,7 +819,7 @@ namespace Google.Protobuf } } - public void WritePackedUInt64Array(int fieldNumber, string fieldName, RepeatedField list) + public void WritePackedUInt64Array(int fieldNumber, RepeatedField list) { if (list.Count == 0) { @@ -945,7 +834,7 @@ namespace Google.Protobuf } } - public void WritePackedFixed64Array(int fieldNumber, string fieldName, RepeatedField list) + public void WritePackedFixed64Array(int fieldNumber, RepeatedField list) { if (list.Count == 0) { @@ -960,7 +849,7 @@ namespace Google.Protobuf } } - public void WritePackedSFixed64Array(int fieldNumber, string fieldName, RepeatedField list) + public void WritePackedSFixed64Array(int fieldNumber, RepeatedField list) { if (list.Count == 0) { @@ -975,7 +864,7 @@ namespace Google.Protobuf } } - public void WritePackedDoubleArray(int fieldNumber, string fieldName, RepeatedField list) + public void WritePackedDoubleArray(int fieldNumber, RepeatedField list) { if (list.Count == 0) { @@ -990,7 +879,7 @@ namespace Google.Protobuf } } - public void WritePackedFloatArray(int fieldNumber, string fieldName, RepeatedField list) + public void WritePackedFloatArray(int fieldNumber, RepeatedField list) { if (list.Count == 0) { @@ -1005,7 +894,7 @@ namespace Google.Protobuf } } - public void WritePackedEnumArray(int fieldNumber, string fieldName, RepeatedField list) + public void WritePackedEnumArray(int fieldNumber, RepeatedField list) where T : struct, IComparable, IFormattable { if (list.Count == 0) diff --git a/csharp/src/ProtocolBuffers/DescriptorProtos/DescriptorProtoFile.cs b/csharp/src/ProtocolBuffers/DescriptorProtos/DescriptorProtoFile.cs index eb96dfcf..f4af4e2c 100644 --- a/csharp/src/ProtocolBuffers/DescriptorProtos/DescriptorProtoFile.cs +++ b/csharp/src/ProtocolBuffers/DescriptorProtos/DescriptorProtoFile.cs @@ -323,9 +323,8 @@ namespace Google.Protobuf.DescriptorProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; - output.WriteMessageArray(1, fieldNames[0], file_); + public void WriteTo(pb::CodedOutputStream output) { + output.WriteMessageArray(1, file_); } public int CalculateSize() { @@ -342,16 +341,9 @@ namespace Google.Protobuf.DescriptorProtos { file_.Add(other.file_); } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -361,7 +353,7 @@ namespace Google.Protobuf.DescriptorProtos { } break; case 10: { - input.ReadMessageArray(tag, fieldName, file_, global::Google.Protobuf.DescriptorProtos.FileDescriptorProto.Parser); + input.ReadMessageArray(tag, file_, global::Google.Protobuf.DescriptorProtos.FileDescriptorProto.Parser); break; } } @@ -510,29 +502,28 @@ namespace Google.Protobuf.DescriptorProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (Name != "") { - output.WriteString(1, fieldNames[4], Name); + output.WriteString(1, Name); } if (Package != "") { - output.WriteString(2, fieldNames[6], Package); + output.WriteString(2, Package); } - output.WriteStringArray(3, fieldNames[0], dependency_); - output.WriteMessageArray(4, fieldNames[3], messageType_); - output.WriteMessageArray(5, fieldNames[1], enumType_); - output.WriteMessageArray(6, fieldNames[8], service_); - output.WriteMessageArray(7, fieldNames[2], extension_); + output.WriteStringArray(3, dependency_); + output.WriteMessageArray(4, messageType_); + output.WriteMessageArray(5, enumType_); + output.WriteMessageArray(6, service_); + output.WriteMessageArray(7, extension_); if (options_ != null) { - output.WriteMessage(8, fieldNames[5], Options); + output.WriteMessage(8, Options); } if (sourceCodeInfo_ != null) { - output.WriteMessage(9, fieldNames[9], SourceCodeInfo); + output.WriteMessage(9, SourceCodeInfo); } - output.WriteInt32Array(10, fieldNames[7], publicDependency_); - output.WriteInt32Array(11, fieldNames[11], weakDependency_); + output.WriteInt32Array(10, publicDependency_); + output.WriteInt32Array(11, weakDependency_); if (Syntax != "") { - output.WriteString(12, fieldNames[10], Syntax); + output.WriteString(12, Syntax); } } @@ -625,16 +616,9 @@ namespace Google.Protobuf.DescriptorProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -644,31 +628,31 @@ namespace Google.Protobuf.DescriptorProtos { } break; case 10: { - input.ReadString(ref name_); + name_ = input.ReadString(); break; } case 18: { - input.ReadString(ref package_); + package_ = input.ReadString(); break; } case 26: { - input.ReadStringArray(tag, fieldName, dependency_); + input.ReadStringArray(tag, dependency_); break; } case 34: { - input.ReadMessageArray(tag, fieldName, messageType_, global::Google.Protobuf.DescriptorProtos.DescriptorProto.Parser); + input.ReadMessageArray(tag, messageType_, global::Google.Protobuf.DescriptorProtos.DescriptorProto.Parser); break; } case 42: { - input.ReadMessageArray(tag, fieldName, enumType_, global::Google.Protobuf.DescriptorProtos.EnumDescriptorProto.Parser); + input.ReadMessageArray(tag, enumType_, global::Google.Protobuf.DescriptorProtos.EnumDescriptorProto.Parser); break; } case 50: { - input.ReadMessageArray(tag, fieldName, service_, global::Google.Protobuf.DescriptorProtos.ServiceDescriptorProto.Parser); + input.ReadMessageArray(tag, service_, global::Google.Protobuf.DescriptorProtos.ServiceDescriptorProto.Parser); break; } case 58: { - input.ReadMessageArray(tag, fieldName, extension_, global::Google.Protobuf.DescriptorProtos.FieldDescriptorProto.Parser); + input.ReadMessageArray(tag, extension_, global::Google.Protobuf.DescriptorProtos.FieldDescriptorProto.Parser); break; } case 66: { @@ -687,16 +671,16 @@ namespace Google.Protobuf.DescriptorProtos { } case 82: case 80: { - input.ReadInt32Array(tag, fieldName, publicDependency_); + input.ReadInt32Array(tag, publicDependency_); break; } case 90: case 88: { - input.ReadInt32Array(tag, fieldName, weakDependency_); + input.ReadInt32Array(tag, weakDependency_); break; } case 98: { - input.ReadString(ref syntax_); + syntax_ = input.ReadString(); break; } } @@ -825,22 +809,21 @@ namespace Google.Protobuf.DescriptorProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (Name != "") { - output.WriteString(1, fieldNames[4], Name); + output.WriteString(1, Name); } - output.WriteMessageArray(2, fieldNames[3], field_); - output.WriteMessageArray(3, fieldNames[5], nestedType_); - output.WriteMessageArray(4, fieldNames[0], enumType_); - output.WriteMessageArray(5, fieldNames[2], extensionRange_); - output.WriteMessageArray(6, fieldNames[1], extension_); + output.WriteMessageArray(2, field_); + output.WriteMessageArray(3, nestedType_); + output.WriteMessageArray(4, enumType_); + output.WriteMessageArray(5, extensionRange_); + output.WriteMessageArray(6, extension_); if (options_ != null) { - output.WriteMessage(7, fieldNames[7], Options); + output.WriteMessage(7, Options); } - output.WriteMessageArray(8, fieldNames[6], oneofDecl_); - output.WriteMessageArray(9, fieldNames[9], reservedRange_); - output.WriteStringArray(10, fieldNames[8], reservedName_); + output.WriteMessageArray(8, oneofDecl_); + output.WriteMessageArray(9, reservedRange_); + output.WriteStringArray(10, reservedName_); } public int CalculateSize() { @@ -905,16 +888,9 @@ namespace Google.Protobuf.DescriptorProtos { reservedName_.Add(other.reservedName_); } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -924,27 +900,27 @@ namespace Google.Protobuf.DescriptorProtos { } break; case 10: { - input.ReadString(ref name_); + name_ = input.ReadString(); break; } case 18: { - input.ReadMessageArray(tag, fieldName, field_, global::Google.Protobuf.DescriptorProtos.FieldDescriptorProto.Parser); + input.ReadMessageArray(tag, field_, global::Google.Protobuf.DescriptorProtos.FieldDescriptorProto.Parser); break; } case 26: { - input.ReadMessageArray(tag, fieldName, nestedType_, global::Google.Protobuf.DescriptorProtos.DescriptorProto.Parser); + input.ReadMessageArray(tag, nestedType_, global::Google.Protobuf.DescriptorProtos.DescriptorProto.Parser); break; } case 34: { - input.ReadMessageArray(tag, fieldName, enumType_, global::Google.Protobuf.DescriptorProtos.EnumDescriptorProto.Parser); + input.ReadMessageArray(tag, enumType_, global::Google.Protobuf.DescriptorProtos.EnumDescriptorProto.Parser); break; } case 42: { - input.ReadMessageArray(tag, fieldName, extensionRange_, global::Google.Protobuf.DescriptorProtos.DescriptorProto.Types.ExtensionRange.Parser); + input.ReadMessageArray(tag, extensionRange_, global::Google.Protobuf.DescriptorProtos.DescriptorProto.Types.ExtensionRange.Parser); break; } case 50: { - input.ReadMessageArray(tag, fieldName, extension_, global::Google.Protobuf.DescriptorProtos.FieldDescriptorProto.Parser); + input.ReadMessageArray(tag, extension_, global::Google.Protobuf.DescriptorProtos.FieldDescriptorProto.Parser); break; } case 58: { @@ -955,15 +931,15 @@ namespace Google.Protobuf.DescriptorProtos { break; } case 66: { - input.ReadMessageArray(tag, fieldName, oneofDecl_, global::Google.Protobuf.DescriptorProtos.OneofDescriptorProto.Parser); + input.ReadMessageArray(tag, oneofDecl_, global::Google.Protobuf.DescriptorProtos.OneofDescriptorProto.Parser); break; } case 74: { - input.ReadMessageArray(tag, fieldName, reservedRange_, global::Google.Protobuf.DescriptorProtos.DescriptorProto.Types.ReservedRange.Parser); + input.ReadMessageArray(tag, reservedRange_, global::Google.Protobuf.DescriptorProtos.DescriptorProto.Types.ReservedRange.Parser); break; } case 82: { - input.ReadStringArray(tag, fieldName, reservedName_); + input.ReadStringArray(tag, reservedName_); break; } } @@ -1031,13 +1007,12 @@ namespace Google.Protobuf.DescriptorProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (Start != 0) { - output.WriteInt32(1, fieldNames[1], Start); + output.WriteInt32(1, Start); } if (End != 0) { - output.WriteInt32(2, fieldNames[0], End); + output.WriteInt32(2, End); } } @@ -1063,16 +1038,9 @@ namespace Google.Protobuf.DescriptorProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -1082,11 +1050,11 @@ namespace Google.Protobuf.DescriptorProtos { } break; case 8: { - input.ReadInt32(ref start_); + start_ = input.ReadInt32(); break; } case 16: { - input.ReadInt32(ref end_); + end_ = input.ReadInt32(); break; } } @@ -1153,13 +1121,12 @@ namespace Google.Protobuf.DescriptorProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (Start != 0) { - output.WriteInt32(1, fieldNames[1], Start); + output.WriteInt32(1, Start); } if (End != 0) { - output.WriteInt32(2, fieldNames[0], End); + output.WriteInt32(2, End); } } @@ -1185,16 +1152,9 @@ namespace Google.Protobuf.DescriptorProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -1204,11 +1164,11 @@ namespace Google.Protobuf.DescriptorProtos { } break; case 8: { - input.ReadInt32(ref start_); + start_ = input.ReadInt32(); break; } case 16: { - input.ReadInt32(ref end_); + end_ = input.ReadInt32(); break; } } @@ -1348,34 +1308,33 @@ namespace Google.Protobuf.DescriptorProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (Name != "") { - output.WriteString(1, fieldNames[3], Name); + output.WriteString(1, Name); } if (Extendee != "") { - output.WriteString(2, fieldNames[1], Extendee); + output.WriteString(2, Extendee); } if (Number != 0) { - output.WriteInt32(3, fieldNames[4], Number); + output.WriteInt32(3, Number); } if (Label != global::Google.Protobuf.DescriptorProtos.FieldDescriptorProto.Types.Label.LABEL_OPTIONAL) { - output.WriteEnum(4, fieldNames[2], (int) Label); + output.WriteEnum(4, (int) Label); } if (Type != global::Google.Protobuf.DescriptorProtos.FieldDescriptorProto.Types.Type.TYPE_DOUBLE) { - output.WriteEnum(5, fieldNames[7], (int) Type); + output.WriteEnum(5, (int) Type); } if (TypeName != "") { - output.WriteString(6, fieldNames[8], TypeName); + output.WriteString(6, TypeName); } if (DefaultValue != "") { - output.WriteString(7, fieldNames[0], DefaultValue); + output.WriteString(7, DefaultValue); } if (options_ != null) { - output.WriteMessage(8, fieldNames[6], Options); + output.WriteMessage(8, Options); } if (OneofIndex != 0) { - output.WriteInt32(9, fieldNames[5], OneofIndex); + output.WriteInt32(9, OneofIndex); } } @@ -1446,16 +1405,9 @@ namespace Google.Protobuf.DescriptorProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -1465,33 +1417,31 @@ namespace Google.Protobuf.DescriptorProtos { } break; case 10: { - input.ReadString(ref name_); + name_ = input.ReadString(); break; } case 18: { - input.ReadString(ref extendee_); + extendee_ = input.ReadString(); break; } case 24: { - input.ReadInt32(ref number_); + number_ = input.ReadInt32(); break; } case 32: { - int tmp = 0; - input.ReadEnum(ref tmp); - label_ = (global::Google.Protobuf.DescriptorProtos.FieldDescriptorProto.Types.Label) tmp;break; + label_ = (global::Google.Protobuf.DescriptorProtos.FieldDescriptorProto.Types.Label) input.ReadEnum(); + break; } case 40: { - int tmp = 0; - input.ReadEnum(ref tmp); - type_ = (global::Google.Protobuf.DescriptorProtos.FieldDescriptorProto.Types.Type) tmp;break; + type_ = (global::Google.Protobuf.DescriptorProtos.FieldDescriptorProto.Types.Type) input.ReadEnum(); + break; } case 50: { - input.ReadString(ref typeName_); + typeName_ = input.ReadString(); break; } case 58: { - input.ReadString(ref defaultValue_); + defaultValue_ = input.ReadString(); break; } case 66: { @@ -1502,7 +1452,7 @@ namespace Google.Protobuf.DescriptorProtos { break; } case 72: { - input.ReadInt32(ref oneofIndex_); + oneofIndex_ = input.ReadInt32(); break; } } @@ -1592,10 +1542,9 @@ namespace Google.Protobuf.DescriptorProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (Name != "") { - output.WriteString(1, fieldNames[0], Name); + output.WriteString(1, Name); } } @@ -1615,16 +1564,9 @@ namespace Google.Protobuf.DescriptorProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -1634,7 +1576,7 @@ namespace Google.Protobuf.DescriptorProtos { } break; case 10: { - input.ReadString(ref name_); + name_ = input.ReadString(); break; } } @@ -1707,14 +1649,13 @@ namespace Google.Protobuf.DescriptorProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (Name != "") { - output.WriteString(1, fieldNames[0], Name); + output.WriteString(1, Name); } - output.WriteMessageArray(2, fieldNames[2], value_); + output.WriteMessageArray(2, value_); if (options_ != null) { - output.WriteMessage(3, fieldNames[1], Options); + output.WriteMessage(3, Options); } } @@ -1747,16 +1688,9 @@ namespace Google.Protobuf.DescriptorProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -1766,11 +1700,11 @@ namespace Google.Protobuf.DescriptorProtos { } break; case 10: { - input.ReadString(ref name_); + name_ = input.ReadString(); break; } case 18: { - input.ReadMessageArray(tag, fieldName, value_, global::Google.Protobuf.DescriptorProtos.EnumValueDescriptorProto.Parser); + input.ReadMessageArray(tag, value_, global::Google.Protobuf.DescriptorProtos.EnumValueDescriptorProto.Parser); break; } case 26: { @@ -1852,16 +1786,15 @@ namespace Google.Protobuf.DescriptorProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (Name != "") { - output.WriteString(1, fieldNames[0], Name); + output.WriteString(1, Name); } if (Number != 0) { - output.WriteInt32(2, fieldNames[1], Number); + output.WriteInt32(2, Number); } if (options_ != null) { - output.WriteMessage(3, fieldNames[2], Options); + output.WriteMessage(3, Options); } } @@ -1896,16 +1829,9 @@ namespace Google.Protobuf.DescriptorProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -1915,11 +1841,11 @@ namespace Google.Protobuf.DescriptorProtos { } break; case 10: { - input.ReadString(ref name_); + name_ = input.ReadString(); break; } case 16: { - input.ReadInt32(ref number_); + number_ = input.ReadInt32(); break; } case 26: { @@ -1999,14 +1925,13 @@ namespace Google.Protobuf.DescriptorProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (Name != "") { - output.WriteString(1, fieldNames[1], Name); + output.WriteString(1, Name); } - output.WriteMessageArray(2, fieldNames[0], method_); + output.WriteMessageArray(2, method_); if (options_ != null) { - output.WriteMessage(3, fieldNames[2], Options); + output.WriteMessage(3, Options); } } @@ -2039,16 +1964,9 @@ namespace Google.Protobuf.DescriptorProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -2058,11 +1976,11 @@ namespace Google.Protobuf.DescriptorProtos { } break; case 10: { - input.ReadString(ref name_); + name_ = input.ReadString(); break; } case 18: { - input.ReadMessageArray(tag, fieldName, method_, global::Google.Protobuf.DescriptorProtos.MethodDescriptorProto.Parser); + input.ReadMessageArray(tag, method_, global::Google.Protobuf.DescriptorProtos.MethodDescriptorProto.Parser); break; } case 26: { @@ -2174,25 +2092,24 @@ namespace Google.Protobuf.DescriptorProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (Name != "") { - output.WriteString(1, fieldNames[2], Name); + output.WriteString(1, Name); } if (InputType != "") { - output.WriteString(2, fieldNames[1], InputType); + output.WriteString(2, InputType); } if (OutputType != "") { - output.WriteString(3, fieldNames[4], OutputType); + output.WriteString(3, OutputType); } if (options_ != null) { - output.WriteMessage(4, fieldNames[3], Options); + output.WriteMessage(4, Options); } if (ClientStreaming != false) { - output.WriteBool(5, fieldNames[0], ClientStreaming); + output.WriteBool(5, ClientStreaming); } if (ServerStreaming != false) { - output.WriteBool(6, fieldNames[5], ServerStreaming); + output.WriteBool(6, ServerStreaming); } } @@ -2245,16 +2162,9 @@ namespace Google.Protobuf.DescriptorProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -2264,15 +2174,15 @@ namespace Google.Protobuf.DescriptorProtos { } break; case 10: { - input.ReadString(ref name_); + name_ = input.ReadString(); break; } case 18: { - input.ReadString(ref inputType_); + inputType_ = input.ReadString(); break; } case 26: { - input.ReadString(ref outputType_); + outputType_ = input.ReadString(); break; } case 34: { @@ -2283,11 +2193,11 @@ namespace Google.Protobuf.DescriptorProtos { break; } case 40: { - input.ReadBool(ref clientStreaming_); + clientStreaming_ = input.ReadBool(); break; } case 48: { - input.ReadBool(ref serverStreaming_); + serverStreaming_ = input.ReadBool(); break; } } @@ -2482,51 +2392,50 @@ namespace Google.Protobuf.DescriptorProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (JavaPackage != "") { - output.WriteString(1, fieldNames[9], JavaPackage); + output.WriteString(1, JavaPackage); } if (JavaOuterClassname != "") { - output.WriteString(8, fieldNames[8], JavaOuterClassname); + output.WriteString(8, JavaOuterClassname); } if (OptimizeFor != global::Google.Protobuf.DescriptorProtos.FileOptions.Types.OptimizeMode.SPEED) { - output.WriteEnum(9, fieldNames[12], (int) OptimizeFor); + output.WriteEnum(9, (int) OptimizeFor); } if (JavaMultipleFiles != false) { - output.WriteBool(10, fieldNames[7], JavaMultipleFiles); + output.WriteBool(10, JavaMultipleFiles); } if (GoPackage != "") { - output.WriteString(11, fieldNames[4], GoPackage); + output.WriteString(11, GoPackage); } if (CcGenericServices != false) { - output.WriteBool(16, fieldNames[1], CcGenericServices); + output.WriteBool(16, CcGenericServices); } if (JavaGenericServices != false) { - output.WriteBool(17, fieldNames[6], JavaGenericServices); + output.WriteBool(17, JavaGenericServices); } if (PyGenericServices != false) { - output.WriteBool(18, fieldNames[13], PyGenericServices); + output.WriteBool(18, PyGenericServices); } if (JavaGenerateEqualsAndHash != false) { - output.WriteBool(20, fieldNames[5], JavaGenerateEqualsAndHash); + output.WriteBool(20, JavaGenerateEqualsAndHash); } if (Deprecated != false) { - output.WriteBool(23, fieldNames[3], Deprecated); + output.WriteBool(23, Deprecated); } if (JavaStringCheckUtf8 != false) { - output.WriteBool(27, fieldNames[10], JavaStringCheckUtf8); + output.WriteBool(27, JavaStringCheckUtf8); } if (CcEnableArenas != false) { - output.WriteBool(31, fieldNames[0], CcEnableArenas); + output.WriteBool(31, CcEnableArenas); } if (ObjcClassPrefix != "") { - output.WriteString(36, fieldNames[11], ObjcClassPrefix); + output.WriteString(36, ObjcClassPrefix); } if (CsharpNamespace != "") { - output.WriteString(37, fieldNames[2], CsharpNamespace); + output.WriteString(37, CsharpNamespace); } - output.WriteMessageArray(999, fieldNames[14], uninterpretedOption_); + output.WriteMessageArray(999, uninterpretedOption_); } public int CalculateSize() { @@ -2627,16 +2536,9 @@ namespace Google.Protobuf.DescriptorProtos { uninterpretedOption_.Add(other.uninterpretedOption_); } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -2646,64 +2548,63 @@ namespace Google.Protobuf.DescriptorProtos { } break; case 10: { - input.ReadString(ref javaPackage_); + javaPackage_ = input.ReadString(); break; } case 66: { - input.ReadString(ref javaOuterClassname_); + javaOuterClassname_ = input.ReadString(); break; } case 72: { - int tmp = 0; - input.ReadEnum(ref tmp); - optimizeFor_ = (global::Google.Protobuf.DescriptorProtos.FileOptions.Types.OptimizeMode) tmp;break; + optimizeFor_ = (global::Google.Protobuf.DescriptorProtos.FileOptions.Types.OptimizeMode) input.ReadEnum(); + break; } case 80: { - input.ReadBool(ref javaMultipleFiles_); + javaMultipleFiles_ = input.ReadBool(); break; } case 90: { - input.ReadString(ref goPackage_); + goPackage_ = input.ReadString(); break; } case 128: { - input.ReadBool(ref ccGenericServices_); + ccGenericServices_ = input.ReadBool(); break; } case 136: { - input.ReadBool(ref javaGenericServices_); + javaGenericServices_ = input.ReadBool(); break; } case 144: { - input.ReadBool(ref pyGenericServices_); + pyGenericServices_ = input.ReadBool(); break; } case 160: { - input.ReadBool(ref javaGenerateEqualsAndHash_); + javaGenerateEqualsAndHash_ = input.ReadBool(); break; } case 184: { - input.ReadBool(ref deprecated_); + deprecated_ = input.ReadBool(); break; } case 216: { - input.ReadBool(ref javaStringCheckUtf8_); + javaStringCheckUtf8_ = input.ReadBool(); break; } case 248: { - input.ReadBool(ref ccEnableArenas_); + ccEnableArenas_ = input.ReadBool(); break; } case 290: { - input.ReadString(ref objcClassPrefix_); + objcClassPrefix_ = input.ReadString(); break; } case 298: { - input.ReadString(ref csharpNamespace_); + csharpNamespace_ = input.ReadString(); break; } case 7994: { - input.ReadMessageArray(tag, fieldName, uninterpretedOption_, global::Google.Protobuf.DescriptorProtos.UninterpretedOption.Parser); + input.ReadMessageArray(tag, uninterpretedOption_, global::Google.Protobuf.DescriptorProtos.UninterpretedOption.Parser); break; } } @@ -2810,21 +2711,20 @@ namespace Google.Protobuf.DescriptorProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (MessageSetWireFormat != false) { - output.WriteBool(1, fieldNames[2], MessageSetWireFormat); + output.WriteBool(1, MessageSetWireFormat); } if (NoStandardDescriptorAccessor != false) { - output.WriteBool(2, fieldNames[3], NoStandardDescriptorAccessor); + output.WriteBool(2, NoStandardDescriptorAccessor); } if (Deprecated != false) { - output.WriteBool(3, fieldNames[0], Deprecated); + output.WriteBool(3, Deprecated); } if (MapEntry != false) { - output.WriteBool(7, fieldNames[1], MapEntry); + output.WriteBool(7, MapEntry); } - output.WriteMessageArray(999, fieldNames[4], uninterpretedOption_); + output.WriteMessageArray(999, uninterpretedOption_); } public int CalculateSize() { @@ -2865,16 +2765,9 @@ namespace Google.Protobuf.DescriptorProtos { uninterpretedOption_.Add(other.uninterpretedOption_); } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -2884,23 +2777,23 @@ namespace Google.Protobuf.DescriptorProtos { } break; case 8: { - input.ReadBool(ref messageSetWireFormat_); + messageSetWireFormat_ = input.ReadBool(); break; } case 16: { - input.ReadBool(ref noStandardDescriptorAccessor_); + noStandardDescriptorAccessor_ = input.ReadBool(); break; } case 24: { - input.ReadBool(ref deprecated_); + deprecated_ = input.ReadBool(); break; } case 56: { - input.ReadBool(ref mapEntry_); + mapEntry_ = input.ReadBool(); break; } case 7994: { - input.ReadMessageArray(tag, fieldName, uninterpretedOption_, global::Google.Protobuf.DescriptorProtos.UninterpretedOption.Parser); + input.ReadMessageArray(tag, uninterpretedOption_, global::Google.Protobuf.DescriptorProtos.UninterpretedOption.Parser); break; } } @@ -3015,27 +2908,26 @@ namespace Google.Protobuf.DescriptorProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (Ctype != global::Google.Protobuf.DescriptorProtos.FieldOptions.Types.CType.STRING) { - output.WriteEnum(1, fieldNames[0], (int) Ctype); + output.WriteEnum(1, (int) Ctype); } if (Packed != false) { - output.WriteBool(2, fieldNames[4], Packed); + output.WriteBool(2, Packed); } if (Deprecated != false) { - output.WriteBool(3, fieldNames[1], Deprecated); + output.WriteBool(3, Deprecated); } if (Lazy != false) { - output.WriteBool(5, fieldNames[3], Lazy); + output.WriteBool(5, Lazy); } if (Jstype != global::Google.Protobuf.DescriptorProtos.FieldOptions.Types.JSType.JS_NORMAL) { - output.WriteEnum(6, fieldNames[2], (int) Jstype); + output.WriteEnum(6, (int) Jstype); } if (Weak != false) { - output.WriteBool(10, fieldNames[6], Weak); + output.WriteBool(10, Weak); } - output.WriteMessageArray(999, fieldNames[5], uninterpretedOption_); + output.WriteMessageArray(999, uninterpretedOption_); } public int CalculateSize() { @@ -3088,16 +2980,9 @@ namespace Google.Protobuf.DescriptorProtos { uninterpretedOption_.Add(other.uninterpretedOption_); } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -3107,33 +2992,31 @@ namespace Google.Protobuf.DescriptorProtos { } break; case 8: { - int tmp = 0; - input.ReadEnum(ref tmp); - ctype_ = (global::Google.Protobuf.DescriptorProtos.FieldOptions.Types.CType) tmp;break; + ctype_ = (global::Google.Protobuf.DescriptorProtos.FieldOptions.Types.CType) input.ReadEnum(); + break; } case 16: { - input.ReadBool(ref packed_); + packed_ = input.ReadBool(); break; } case 24: { - input.ReadBool(ref deprecated_); + deprecated_ = input.ReadBool(); break; } case 40: { - input.ReadBool(ref lazy_); + lazy_ = input.ReadBool(); break; } case 48: { - int tmp = 0; - input.ReadEnum(ref tmp); - jstype_ = (global::Google.Protobuf.DescriptorProtos.FieldOptions.Types.JSType) tmp;break; + jstype_ = (global::Google.Protobuf.DescriptorProtos.FieldOptions.Types.JSType) input.ReadEnum(); + break; } case 80: { - input.ReadBool(ref weak_); + weak_ = input.ReadBool(); break; } case 7994: { - input.ReadMessageArray(tag, fieldName, uninterpretedOption_, global::Google.Protobuf.DescriptorProtos.UninterpretedOption.Parser); + input.ReadMessageArray(tag, uninterpretedOption_, global::Google.Protobuf.DescriptorProtos.UninterpretedOption.Parser); break; } } @@ -3226,15 +3109,14 @@ namespace Google.Protobuf.DescriptorProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (AllowAlias != false) { - output.WriteBool(2, fieldNames[0], AllowAlias); + output.WriteBool(2, AllowAlias); } if (Deprecated != false) { - output.WriteBool(3, fieldNames[1], Deprecated); + output.WriteBool(3, Deprecated); } - output.WriteMessageArray(999, fieldNames[2], uninterpretedOption_); + output.WriteMessageArray(999, uninterpretedOption_); } public int CalculateSize() { @@ -3263,16 +3145,9 @@ namespace Google.Protobuf.DescriptorProtos { uninterpretedOption_.Add(other.uninterpretedOption_); } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -3282,15 +3157,15 @@ namespace Google.Protobuf.DescriptorProtos { } break; case 16: { - input.ReadBool(ref allowAlias_); + allowAlias_ = input.ReadBool(); break; } case 24: { - input.ReadBool(ref deprecated_); + deprecated_ = input.ReadBool(); break; } case 7994: { - input.ReadMessageArray(tag, fieldName, uninterpretedOption_, global::Google.Protobuf.DescriptorProtos.UninterpretedOption.Parser); + input.ReadMessageArray(tag, uninterpretedOption_, global::Google.Protobuf.DescriptorProtos.UninterpretedOption.Parser); break; } } @@ -3355,12 +3230,11 @@ namespace Google.Protobuf.DescriptorProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (Deprecated != false) { - output.WriteBool(1, fieldNames[0], Deprecated); + output.WriteBool(1, Deprecated); } - output.WriteMessageArray(999, fieldNames[1], uninterpretedOption_); + output.WriteMessageArray(999, uninterpretedOption_); } public int CalculateSize() { @@ -3383,16 +3257,9 @@ namespace Google.Protobuf.DescriptorProtos { uninterpretedOption_.Add(other.uninterpretedOption_); } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -3402,11 +3269,11 @@ namespace Google.Protobuf.DescriptorProtos { } break; case 8: { - input.ReadBool(ref deprecated_); + deprecated_ = input.ReadBool(); break; } case 7994: { - input.ReadMessageArray(tag, fieldName, uninterpretedOption_, global::Google.Protobuf.DescriptorProtos.UninterpretedOption.Parser); + input.ReadMessageArray(tag, uninterpretedOption_, global::Google.Protobuf.DescriptorProtos.UninterpretedOption.Parser); break; } } @@ -3471,12 +3338,11 @@ namespace Google.Protobuf.DescriptorProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (Deprecated != false) { - output.WriteBool(33, fieldNames[0], Deprecated); + output.WriteBool(33, Deprecated); } - output.WriteMessageArray(999, fieldNames[1], uninterpretedOption_); + output.WriteMessageArray(999, uninterpretedOption_); } public int CalculateSize() { @@ -3499,16 +3365,9 @@ namespace Google.Protobuf.DescriptorProtos { uninterpretedOption_.Add(other.uninterpretedOption_); } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -3518,11 +3377,11 @@ namespace Google.Protobuf.DescriptorProtos { } break; case 264: { - input.ReadBool(ref deprecated_); + deprecated_ = input.ReadBool(); break; } case 7994: { - input.ReadMessageArray(tag, fieldName, uninterpretedOption_, global::Google.Protobuf.DescriptorProtos.UninterpretedOption.Parser); + input.ReadMessageArray(tag, uninterpretedOption_, global::Google.Protobuf.DescriptorProtos.UninterpretedOption.Parser); break; } } @@ -3587,12 +3446,11 @@ namespace Google.Protobuf.DescriptorProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (Deprecated != false) { - output.WriteBool(33, fieldNames[0], Deprecated); + output.WriteBool(33, Deprecated); } - output.WriteMessageArray(999, fieldNames[1], uninterpretedOption_); + output.WriteMessageArray(999, uninterpretedOption_); } public int CalculateSize() { @@ -3615,16 +3473,9 @@ namespace Google.Protobuf.DescriptorProtos { uninterpretedOption_.Add(other.uninterpretedOption_); } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -3634,11 +3485,11 @@ namespace Google.Protobuf.DescriptorProtos { } break; case 264: { - input.ReadBool(ref deprecated_); + deprecated_ = input.ReadBool(); break; } case 7994: { - input.ReadMessageArray(tag, fieldName, uninterpretedOption_, global::Google.Protobuf.DescriptorProtos.UninterpretedOption.Parser); + input.ReadMessageArray(tag, uninterpretedOption_, global::Google.Protobuf.DescriptorProtos.UninterpretedOption.Parser); break; } } @@ -3753,26 +3604,25 @@ namespace Google.Protobuf.DescriptorProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; - output.WriteMessageArray(2, fieldNames[3], name_); + public void WriteTo(pb::CodedOutputStream output) { + output.WriteMessageArray(2, name_); if (IdentifierValue != "") { - output.WriteString(3, fieldNames[2], IdentifierValue); + output.WriteString(3, IdentifierValue); } if (PositiveIntValue != 0UL) { - output.WriteUInt64(4, fieldNames[5], PositiveIntValue); + output.WriteUInt64(4, PositiveIntValue); } if (NegativeIntValue != 0L) { - output.WriteInt64(5, fieldNames[4], NegativeIntValue); + output.WriteInt64(5, NegativeIntValue); } if (DoubleValue != 0D) { - output.WriteDouble(6, fieldNames[1], DoubleValue); + output.WriteDouble(6, DoubleValue); } if (StringValue != pb::ByteString.Empty) { - output.WriteBytes(7, fieldNames[6], StringValue); + output.WriteBytes(7, StringValue); } if (AggregateValue != "") { - output.WriteString(8, fieldNames[0], AggregateValue); + output.WriteString(8, AggregateValue); } } @@ -3826,16 +3676,9 @@ namespace Google.Protobuf.DescriptorProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -3845,31 +3688,31 @@ namespace Google.Protobuf.DescriptorProtos { } break; case 18: { - input.ReadMessageArray(tag, fieldName, name_, global::Google.Protobuf.DescriptorProtos.UninterpretedOption.Types.NamePart.Parser); + input.ReadMessageArray(tag, name_, global::Google.Protobuf.DescriptorProtos.UninterpretedOption.Types.NamePart.Parser); break; } case 26: { - input.ReadString(ref identifierValue_); + identifierValue_ = input.ReadString(); break; } case 32: { - input.ReadUInt64(ref positiveIntValue_); + positiveIntValue_ = input.ReadUInt64(); break; } case 40: { - input.ReadInt64(ref negativeIntValue_); + negativeIntValue_ = input.ReadInt64(); break; } case 49: { - input.ReadDouble(ref doubleValue_); + doubleValue_ = input.ReadDouble(); break; } case 58: { - input.ReadBytes(ref stringValue_); + stringValue_ = input.ReadBytes(); break; } case 66: { - input.ReadString(ref aggregateValue_); + aggregateValue_ = input.ReadString(); break; } } @@ -3937,13 +3780,12 @@ namespace Google.Protobuf.DescriptorProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; + public void WriteTo(pb::CodedOutputStream output) { if (NamePart_ != "") { - output.WriteString(1, fieldNames[1], NamePart_); + output.WriteString(1, NamePart_); } if (IsExtension != false) { - output.WriteBool(2, fieldNames[0], IsExtension); + output.WriteBool(2, IsExtension); } } @@ -3969,16 +3811,9 @@ namespace Google.Protobuf.DescriptorProtos { } } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -3988,11 +3823,11 @@ namespace Google.Protobuf.DescriptorProtos { } break; case 10: { - input.ReadString(ref namePart_); + namePart_ = input.ReadString(); break; } case 16: { - input.ReadBool(ref isExtension_); + isExtension_ = input.ReadBool(); break; } } @@ -4052,9 +3887,8 @@ namespace Google.Protobuf.DescriptorProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; - output.WriteMessageArray(1, fieldNames[0], location_); + public void WriteTo(pb::CodedOutputStream output) { + output.WriteMessageArray(1, location_); } public int CalculateSize() { @@ -4071,16 +3905,9 @@ namespace Google.Protobuf.DescriptorProtos { location_.Add(other.location_); } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -4090,7 +3917,7 @@ namespace Google.Protobuf.DescriptorProtos { } break; case 10: { - input.ReadMessageArray(tag, fieldName, location_, global::Google.Protobuf.DescriptorProtos.SourceCodeInfo.Types.Location.Parser); + input.ReadMessageArray(tag, location_, global::Google.Protobuf.DescriptorProtos.SourceCodeInfo.Types.Location.Parser); break; } } @@ -4182,17 +4009,16 @@ namespace Google.Protobuf.DescriptorProtos { return hash; } - public void WriteTo(pb::ICodedOutputStream output) { - string[] fieldNames = _fieldNames; - output.WritePackedInt32Array(1, fieldNames[2], path_); - output.WritePackedInt32Array(2, fieldNames[3], span_); + public void WriteTo(pb::CodedOutputStream output) { + output.WritePackedInt32Array(1, path_); + output.WritePackedInt32Array(2, span_); if (LeadingComments != "") { - output.WriteString(3, fieldNames[0], LeadingComments); + output.WriteString(3, LeadingComments); } if (TrailingComments != "") { - output.WriteString(4, fieldNames[4], TrailingComments); + output.WriteString(4, TrailingComments); } - output.WriteStringArray(6, fieldNames[1], leadingDetachedComments_); + output.WriteStringArray(6, leadingDetachedComments_); } public int CalculateSize() { @@ -4248,16 +4074,9 @@ namespace Google.Protobuf.DescriptorProtos { leadingDetachedComments_.Add(other.leadingDetachedComments_); } - public void MergeFrom(pb::ICodedInputStream input) { + public void MergeFrom(pb::CodedInputStream input) { uint tag; - string fieldName; - while (input.ReadTag(out tag, out fieldName)) { - if (tag == 0 && fieldName != null) { - int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal); - if (fieldOrdinal >= 0) { - tag = _fieldTags[fieldOrdinal]; - } - } + while (input.ReadTag(out tag)) { switch(tag) { case 0: throw pb::InvalidProtocolBufferException.InvalidTag(); @@ -4268,24 +4087,24 @@ namespace Google.Protobuf.DescriptorProtos { break; case 10: case 8: { - input.ReadInt32Array(tag, fieldName, path_); + input.ReadInt32Array(tag, path_); break; } case 18: case 16: { - input.ReadInt32Array(tag, fieldName, span_); + input.ReadInt32Array(tag, span_); break; } case 26: { - input.ReadString(ref leadingComments_); + leadingComments_ = input.ReadString(); break; } case 34: { - input.ReadString(ref trailingComments_); + trailingComments_ = input.ReadString(); break; } case 50: { - input.ReadStringArray(tag, fieldName, leadingDetachedComments_); + input.ReadStringArray(tag, leadingDetachedComments_); break; } } diff --git a/csharp/src/ProtocolBuffers/Extensions.cs b/csharp/src/ProtocolBuffers/Extensions.cs index 29288f51..7f23057e 100644 --- a/csharp/src/ProtocolBuffers/Extensions.cs +++ b/csharp/src/ProtocolBuffers/Extensions.cs @@ -49,7 +49,7 @@ namespace Google.Protobuf codedOutput.Flush(); } - public static void WriteTo(this IMessage message, ICodedOutputStream output) + public static void WriteTo(this IMessage message, CodedOutputStream output) { message.WriteTo(output); } diff --git a/csharp/src/ProtocolBuffers/ICodedInputStream.cs b/csharp/src/ProtocolBuffers/ICodedInputStream.cs deleted file mode 100644 index d962e62b..00000000 --- a/csharp/src/ProtocolBuffers/ICodedInputStream.cs +++ /dev/null @@ -1,293 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using Google.Protobuf.Descriptors; - -//Disable warning CS3010: CLS-compliant interfaces must have only CLS-compliant members -#pragma warning disable 3010 - -namespace Google.Protobuf -{ - public interface ICodedInputStream - { - /// - /// Reads any message initialization data expected from the input stream - /// - /// - /// This is primarily used by text formats and unnecessary for protobuffers' own - /// binary format. The API for MessageStart/End was added for consistent handling - /// of output streams regardless of the actual writer implementation. - /// - void ReadMessageStart(); - /// - /// Reads any message finalization data expected from the input stream - /// - /// - /// This is primarily used by text formats and unnecessary for protobuffers' own - /// binary format. The API for MessageStart/End was added for consistent handling - /// of output streams regardless of the actual writer implementation. - /// - void ReadMessageEnd(); - /// - /// Attempt to read a field tag, returning false if we have reached the end - /// of the input data. - /// - /// - /// - /// If fieldTag is non-zero and ReadTag returns true then the value in fieldName - /// may or may not be populated. However, if fieldTag is zero and ReadTag returns - /// true, then fieldName should be populated with a non-null field name. - /// - /// In other words if ReadTag returns true then either fieldTag will be non-zero OR - /// fieldName will be non-zero. In some cases both may be populated, however the - /// builders will always prefer the fieldTag over fieldName. - /// - /// - bool ReadTag(out uint fieldTag, out string fieldName); - - /// - /// Read a double field from the stream. - /// - bool ReadDouble(ref double value); - - /// - /// Read a float field from the stream. - /// - bool ReadFloat(ref float value); - - /// - /// Read a uint64 field from the stream. - /// - bool ReadUInt64(ref ulong value); - - /// - /// Read an int64 field from the stream. - /// - bool ReadInt64(ref long value); - - /// - /// Read an int32 field from the stream. - /// - bool ReadInt32(ref int value); - - /// - /// Read a fixed64 field from the stream. - /// - bool ReadFixed64(ref ulong value); - - /// - /// Read a fixed32 field from the stream. - /// - bool ReadFixed32(ref uint value); - - /// - /// Read a bool field from the stream. - /// - bool ReadBool(ref bool value); - - /// - /// Reads a string field from the stream. - /// - bool ReadString(ref string value); - - /// - /// Reads a group field value from the stream. - /// - void ReadGroup(int fieldNumber, IMessage message); - - /// - /// Reads an embedded message field value from the stream. - /// - void ReadMessage(IMessage message); - - /// - /// Reads a bytes field value from the stream. - /// - bool ReadBytes(ref ByteString value); - - /// - /// Reads a uint32 field value from the stream. - /// - bool ReadUInt32(ref uint value); - - /// - /// Reads an enum field value from the stream. This performs no checking - /// as to whether the enum value is known to the enum type as it was present - /// when the code was generated. - /// - bool ReadEnum(ref int value); - - /// - /// Reads an sfixed32 field value from the stream. - /// - bool ReadSFixed32(ref int value); - - /// - /// Reads an sfixed64 field value from the stream. - /// - bool ReadSFixed64(ref long value); - - /// - /// Reads an sint32 field value from the stream. - /// - bool ReadSInt32(ref int value); - - /// - /// Reads an sint64 field value from the stream. - /// - bool ReadSInt64(ref long value); - - /// - /// Reads an array of primitive values into the list, if the wire-type of fieldTag is length-prefixed and the - /// type is numeric, it will read a packed array. - /// - void ReadPrimitiveArray(FieldType fieldType, uint fieldTag, string fieldName, ICollection list); - - /// - /// Reads an array of primitive values into the list, if the wire-type of fieldTag is length-prefixed, it will - /// read a packed array. - /// - void ReadEnumArray(uint fieldTag, string fieldName, ICollection list) - where T : struct, IComparable, IFormattable; - - /// - /// Reads a set of messages using the to read individual messages. - /// - void ReadMessageArray(uint fieldTag, string fieldName, ICollection list, MessageParser parser) where T : IMessage; - - /// - /// Reads a set of messages using the as a template. - /// - void ReadGroupArray(uint fieldTag, string fieldName, ICollection list, MessageParser parser) where T : IMessage; - - /// - /// Reads a field of any primitive type. Enums, groups and embedded - /// messages are not handled by this method. - /// - bool ReadPrimitiveField(FieldType fieldType, ref object value); - - /// - /// Returns true if the stream has reached the end of the input. This is the - /// case if either the end of the underlying input source has been reached or - /// the stream has reached a limit created using PushLimit. - /// - bool IsAtEnd { get; } - - /// - /// Reads and discards a single field, given its tag value. - /// - /// false if the tag is an end-group tag, in which case - /// nothing is skipped. Otherwise, returns true. - bool SkipField(); - - /// - /// Reads one or more repeated string field values from the stream. - /// - void ReadStringArray(uint fieldTag, string fieldName, ICollection list); - - /// - /// Reads one or more repeated ByteString field values from the stream. - /// - void ReadBytesArray(uint fieldTag, string fieldName, ICollection list); - - /// - /// Reads one or more repeated boolean field values from the stream. - /// - void ReadBoolArray(uint fieldTag, string fieldName, ICollection list); - - /// - /// Reads one or more repeated Int32 field values from the stream. - /// - void ReadInt32Array(uint fieldTag, string fieldName, ICollection list); - - /// - /// Reads one or more repeated SInt32 field values from the stream. - /// - void ReadSInt32Array(uint fieldTag, string fieldName, ICollection list); - - /// - /// Reads one or more repeated UInt32 field values from the stream. - /// - void ReadUInt32Array(uint fieldTag, string fieldName, ICollection list); - - /// - /// Reads one or more repeated Fixed32 field values from the stream. - /// - void ReadFixed32Array(uint fieldTag, string fieldName, ICollection list); - - /// - /// Reads one or more repeated SFixed32 field values from the stream. - /// - void ReadSFixed32Array(uint fieldTag, string fieldName, ICollection list); - - /// - /// Reads one or more repeated Int64 field values from the stream. - /// - void ReadInt64Array(uint fieldTag, string fieldName, ICollection list); - - /// - /// Reads one or more repeated SInt64 field values from the stream. - /// - void ReadSInt64Array(uint fieldTag, string fieldName, ICollection list); - - /// - /// Reads one or more repeated UInt64 field values from the stream. - /// - void ReadUInt64Array(uint fieldTag, string fieldName, ICollection list); - - /// - /// Reads one or more repeated Fixed64 field values from the stream. - /// - void ReadFixed64Array(uint fieldTag, string fieldName, ICollection list); - - /// - /// Reads one or more repeated SFixed64 field values from the stream. - /// - void ReadSFixed64Array(uint fieldTag, string fieldName, ICollection list); - - /// - /// Reads one or more repeated Double field values from the stream. - /// - void ReadDoubleArray(uint fieldTag, string fieldName, ICollection list); - - /// - /// Reads one or more repeated Float field values from the stream. - /// - void ReadFloatArray(uint fieldTag, string fieldName, ICollection list); - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers/ICodedOutputStream.cs b/csharp/src/ProtocolBuffers/ICodedOutputStream.cs deleted file mode 100644 index 921400ac..00000000 --- a/csharp/src/ProtocolBuffers/ICodedOutputStream.cs +++ /dev/null @@ -1,347 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections; -using Google.Protobuf.Collections; -using Google.Protobuf.Descriptors; - -//Disable warning CS3010: CLS-compliant interfaces must have only CLS-compliant members -#pragma warning disable 3010 - -namespace Google.Protobuf -{ - /// - /// Provides an interface that is used write a message. Most often proto buffers are written - /// in their binary form by creating a instance via the CodedOutputStream.CreateInstance - /// static factory. - /// - public interface ICodedOutputStream - { - /// - /// Writes any message initialization data needed to the output stream - /// - /// - /// This is primarily used by text formats and unnecessary for protobuffers' own - /// binary format. The API for MessageStart/End was added for consistent handling - /// of output streams regardless of the actual writer implementation. - /// - void WriteMessageStart(); - /// - /// Writes any message finalization data needed to the output stream - /// - /// - /// This is primarily used by text formats and unnecessary for protobuffers' own - /// binary format. The API for MessageStart/End was added for consistent handling - /// of output streams regardless of the actual writer implementation. - /// - void WriteMessageEnd(); - - /// - /// Indicates that all temporary buffers be written to the final output. - /// - void Flush(); - - /// - /// Writes a field value, including tag, to the stream. - /// - void WriteField(FieldType fieldType, int fieldNumber, string fieldName, object value); - - /// - /// Writes a double field value, including tag, to the stream. - /// - void WriteDouble(int fieldNumber, string fieldName, double value); - - /// - /// Writes a float field value, including tag, to the stream. - /// - void WriteFloat(int fieldNumber, string fieldName, float value); - - /// - /// Writes a uint64 field value, including tag, to the stream. - /// - void WriteUInt64(int fieldNumber, string fieldName, ulong value); - - /// - /// Writes an int64 field value, including tag, to the stream. - /// - void WriteInt64(int fieldNumber, string fieldName, long value); - - /// - /// Writes an int32 field value, including tag, to the stream. - /// - void WriteInt32(int fieldNumber, string fieldName, int value); - - /// - /// Writes a fixed64 field value, including tag, to the stream. - /// - void WriteFixed64(int fieldNumber, string fieldName, ulong value); - - /// - /// Writes a fixed32 field value, including tag, to the stream. - /// - void WriteFixed32(int fieldNumber, string fieldName, uint value); - - /// - /// Writes a bool field value, including tag, to the stream. - /// - void WriteBool(int fieldNumber, string fieldName, bool value); - - /// - /// Writes a string field value, including tag, to the stream. - /// - void WriteString(int fieldNumber, string fieldName, string value); - - /// - /// Writes a group field value, including tag, to the stream. - /// - void WriteGroup(int fieldNumber, string fieldName, IMessage value); - - /// - /// Writes a message field value, including tag, to the stream. - /// - void WriteMessage(int fieldNumber, string fieldName, IMessage value); - - /// - /// Writes a byte array field value, including tag, to the stream. - /// - void WriteBytes(int fieldNumber, string fieldName, ByteString value); - - /// - /// Writes a UInt32 field value, including tag, to the stream. - /// - void WriteUInt32(int fieldNumber, string fieldName, uint value); - - /// - /// Writes an enum field value, including tag, to the stream. - /// - void WriteEnum(int fieldNumber, string fieldName, int value); - - /// - /// Writes a fixed 32-bit field value, including tag, to the stream. - /// - void WriteSFixed32(int fieldNumber, string fieldName, int value); - - /// - /// Writes a signed fixed 64-bit field value, including tag, to the stream. - /// - void WriteSFixed64(int fieldNumber, string fieldName, long value); - - /// - /// Writes a signed 32-bit field value, including tag, to the stream. - /// - void WriteSInt32(int fieldNumber, string fieldName, int value); - - /// - /// Writes a signed 64-bit field value, including tag, to the stream. - /// - void WriteSInt64(int fieldNumber, string fieldName, long value); - - /// - /// Writes a repeated field value, including tag(s), to the stream. - /// - void WriteArray(FieldType fieldType, int fieldNumber, string fieldName, IEnumerable list); - - /// - /// Writes a repeated group value, including tag(s), to the stream. - /// - void WriteGroupArray(int fieldNumber, string fieldName, RepeatedField list) - where T : IMessage; - - /// - /// Writes a repeated message value, including tag(s), to the stream. - /// - void WriteMessageArray(int fieldNumber, string fieldName, RepeatedField list) - where T : IMessage; - - /// - /// Writes a repeated string value, including tag(s), to the stream. - /// - void WriteStringArray(int fieldNumber, string fieldName, RepeatedField list); - - /// - /// Writes a repeated ByteString value, including tag(s), to the stream. - /// - void WriteBytesArray(int fieldNumber, string fieldName, RepeatedField list); - - /// - /// Writes a repeated boolean value, including tag(s), to the stream. - /// - void WriteBoolArray(int fieldNumber, string fieldName, RepeatedField list); - - /// - /// Writes a repeated Int32 value, including tag(s), to the stream. - /// - void WriteInt32Array(int fieldNumber, string fieldName, RepeatedField list); - - /// - /// Writes a repeated SInt32 value, including tag(s), to the stream. - /// - void WriteSInt32Array(int fieldNumber, string fieldName, RepeatedField list); - - /// - /// Writes a repeated UInt32 value, including tag(s), to the stream. - /// - void WriteUInt32Array(int fieldNumber, string fieldName, RepeatedField list); - - /// - /// Writes a repeated Fixed32 value, including tag(s), to the stream. - /// - void WriteFixed32Array(int fieldNumber, string fieldName, RepeatedField list); - - /// - /// Writes a repeated SFixed32 value, including tag(s), to the stream. - /// - void WriteSFixed32Array(int fieldNumber, string fieldName, RepeatedField list); - - /// - /// Writes a repeated Int64 value, including tag(s), to the stream. - /// - void WriteInt64Array(int fieldNumber, string fieldName, RepeatedField list); - - /// - /// Writes a repeated SInt64 value, including tag(s), to the stream. - /// - void WriteSInt64Array(int fieldNumber, string fieldName, RepeatedField list); - - /// - /// Writes a repeated UInt64 value, including tag(s), to the stream. - /// - void WriteUInt64Array(int fieldNumber, string fieldName, RepeatedField list); - - /// - /// Writes a repeated Fixed64 value, including tag(s), to the stream. - /// - void WriteFixed64Array(int fieldNumber, string fieldName, RepeatedField list); - - /// - /// Writes a repeated SFixed64 value, including tag(s), to the stream. - /// - void WriteSFixed64Array(int fieldNumber, string fieldName, RepeatedField list); - - /// - /// Writes a repeated Double value, including tag(s), to the stream. - /// - void WriteDoubleArray(int fieldNumber, string fieldName, RepeatedField list); - - /// - /// Writes a repeated Float value, including tag(s), to the stream. - /// - void WriteFloatArray(int fieldNumber, string fieldName, RepeatedField list); - - /// - /// Writes a repeated enumeration value of type T, including tag(s), to the stream. - /// - void WriteEnumArray(int fieldNumber, string fieldName, RepeatedField list) - where T : struct, IComparable, IFormattable; - - /// - /// Writes a packed repeated primitive, including tag and length, to the stream. - /// - void WritePackedArray(FieldType fieldType, int fieldNumber, string fieldName, IEnumerable list); - - /// - /// Writes a packed repeated boolean, including tag and length, to the stream. - /// - void WritePackedBoolArray(int fieldNumber, string fieldName, RepeatedField list); - - /// - /// Writes a packed repeated Int32, including tag and length, to the stream. - /// - void WritePackedInt32Array(int fieldNumber, string fieldName, RepeatedField list); - - /// - /// Writes a packed repeated SInt32, including tag and length, to the stream. - /// - void WritePackedSInt32Array(int fieldNumber, string fieldName, RepeatedField list); - - /// - /// Writes a packed repeated UInt32, including tag and length, to the stream. - /// - void WritePackedUInt32Array(int fieldNumber, string fieldName, RepeatedField list); - - /// - /// Writes a packed repeated Fixed32, including tag and length, to the stream. - /// - void WritePackedFixed32Array(int fieldNumber, string fieldName, RepeatedField list); - - /// - /// Writes a packed repeated SFixed32, including tag and length, to the stream. - /// - void WritePackedSFixed32Array(int fieldNumber, string fieldName, RepeatedField list); - - /// - /// Writes a packed repeated Int64, including tag and length, to the stream. - /// - void WritePackedInt64Array(int fieldNumber, string fieldName, RepeatedField list); - - /// - /// Writes a packed repeated SInt64, including tag and length, to the stream. - /// - void WritePackedSInt64Array(int fieldNumber, string fieldName, RepeatedField list); - - /// - /// Writes a packed repeated UInt64, including tag and length, to the stream. - /// - void WritePackedUInt64Array(int fieldNumber, string fieldName, RepeatedField list); - - /// - /// Writes a packed repeated Fixed64, including tag and length, to the stream. - /// - void WritePackedFixed64Array(int fieldNumber, string fieldName, RepeatedField list); - - /// - /// Writes a packed repeated SFixed64, including tag and length, to the stream. - /// - void WritePackedSFixed64Array(int fieldNumber, string fieldName, RepeatedField list); - - /// - /// Writes a packed repeated Double, including tag and length, to the stream. - /// - void WritePackedDoubleArray(int fieldNumber, string fieldName, RepeatedField list); - - /// - /// Writes a packed repeated Float, including tag and length, to the stream. - /// - void WritePackedFloatArray(int fieldNumber, string fieldName, RepeatedField list); - - /// - /// Writes a packed repeated enumeration of type T, including tag and length, to the stream. - /// - void WritePackedEnumArray(int fieldNumber, string fieldName, RepeatedField list) - where T : struct, IComparable, IFormattable; - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers/IMessage.cs b/csharp/src/ProtocolBuffers/IMessage.cs index 4e06f6e8..55b6fc5d 100644 --- a/csharp/src/ProtocolBuffers/IMessage.cs +++ b/csharp/src/ProtocolBuffers/IMessage.cs @@ -51,8 +51,8 @@ namespace Google.Protobuf public interface IMessage { - void MergeFrom(ICodedInputStream input); - void WriteTo(ICodedOutputStream output); + void MergeFrom(CodedInputStream input); + void WriteTo(CodedOutputStream output); int CalculateSize(); } diff --git a/csharp/src/ProtocolBuffers/MessageParser.cs b/csharp/src/ProtocolBuffers/MessageParser.cs index 399a9043..722435cc 100644 --- a/csharp/src/ProtocolBuffers/MessageParser.cs +++ b/csharp/src/ProtocolBuffers/MessageParser.cs @@ -47,7 +47,7 @@ namespace Google.Protobuf return message; } - public T ParseFrom(ICodedInputStream input) + public T ParseFrom(CodedInputStream input) { T message = factory(); message.MergeFrom(input); diff --git a/csharp/src/ProtocolBuffers/ProtocolBuffers.csproj b/csharp/src/ProtocolBuffers/ProtocolBuffers.csproj index efd387a2..3a07e87f 100644 --- a/csharp/src/ProtocolBuffers/ProtocolBuffers.csproj +++ b/csharp/src/ProtocolBuffers/ProtocolBuffers.csproj @@ -93,8 +93,6 @@ - - diff --git a/src/google/protobuf/compiler/csharp/csharp_enum_field.cc b/src/google/protobuf/compiler/csharp/csharp_enum_field.cc index 3494b228..19fd50cf 100644 --- a/src/google/protobuf/compiler/csharp/csharp_enum_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_enum_field.cc @@ -54,17 +54,14 @@ EnumFieldGenerator::~EnumFieldGenerator() { } void EnumFieldGenerator::GenerateParsingCode(io::Printer* printer) { - // TODO(jonskeet): Get rid of the temporary variable when we sanitize CodedInputStream not to use ref. printer->Print(variables_, - "int tmp = 0;\n" - "input.ReadEnum(ref tmp);\n" - "$name$_ = ($type_name$) tmp;"); + "$name$_ = ($type_name$) input.ReadEnum();\n"); } void EnumFieldGenerator::GenerateSerializationCode(io::Printer* printer) { printer->Print(variables_, "if ($has_property_check$) {\n" - " output.WriteEnum($number$, fieldNames[$field_ordinal$], (int) $property_name$);\n" + " output.WriteEnum($number$, (int) $property_name$);\n" "}\n"); } @@ -88,18 +85,15 @@ void EnumOneofFieldGenerator::GenerateParsingCode(io::Printer* printer) { // TODO(jonskeet): What about if we read the default value? printer->Print( variables_, - "int enumValue = 0;\n" - "if(input.ReadEnum(ref enumValue)) {\n" - " $oneof_name$_ = enumValue;\n" - " $oneof_name$Case_ = $oneof_property_name$OneofCase.$property_name$;\n" - "}\n"); + "$oneof_name$_ = input.ReadEnum();\n" + "$oneof_name$Case_ = $oneof_property_name$OneofCase.$property_name$;\n"); } void EnumOneofFieldGenerator::GenerateSerializationCode(io::Printer* printer) { printer->Print( variables_, "if ($has_property_check$) {\n" - " output.WriteEnum($number$, fieldNames[$field_ordinal$], (int) $property_name$);\n" + " output.WriteEnum($number$, (int) $property_name$);\n" "}\n"); } diff --git a/src/google/protobuf/compiler/csharp/csharp_message.cc b/src/google/protobuf/compiler/csharp/csharp_message.cc index b5929bcd..aca68fb7 100644 --- a/src/google/protobuf/compiler/csharp/csharp_message.cc +++ b/src/google/protobuf/compiler/csharp/csharp_message.cc @@ -350,9 +350,8 @@ void MessageGenerator::GenerateFrameworkMethods(io::Printer* printer) { void MessageGenerator::GenerateMessageSerializationMethods(io::Printer* printer) { printer->Print( - "public void WriteTo(pb::ICodedOutputStream output) {\n"); + "public void WriteTo(pb::CodedOutputStream output) {\n"); printer->Indent(); - printer->Print("string[] fieldNames = _fieldNames;\n"); // Serialize all the fields for (int i = 0; i < fields_by_number().size(); i++) { @@ -423,21 +422,13 @@ void MessageGenerator::GenerateMergingMethods(io::Printer* printer) { } printer->Outdent(); printer->Print("}\n\n"); - printer->Print("public void MergeFrom(pb::ICodedInputStream input) {\n"); + printer->Print("public void MergeFrom(pb::CodedInputStream input) {\n"); printer->Indent(); printer->Print( "uint tag;\n" - "string fieldName;\n" - "while (input.ReadTag(out tag, out fieldName)) {\n"); + "while (input.ReadTag(out tag)) {\n" + " switch(tag) {\n"); printer->Indent(); - printer->Print( - "if (tag == 0 && fieldName != null) {\n" - " int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal);\n" - " if (fieldOrdinal >= 0) {\n" - " tag = _fieldTags[fieldOrdinal];\n" - " }\n" - "}\n" - "switch(tag) {\n"); printer->Indent(); printer->Print( "case 0:\n" // 0 signals EOF / limit reached diff --git a/src/google/protobuf/compiler/csharp/csharp_message_field.cc b/src/google/protobuf/compiler/csharp/csharp_message_field.cc index 4b7ac88f..804a5ae2 100644 --- a/src/google/protobuf/compiler/csharp/csharp_message_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_message_field.cc @@ -87,6 +87,7 @@ void MessageFieldGenerator::GenerateParsingCode(io::Printer* printer) { "if ($has_not_property_check$) {\n" " $name$_ = new $type_name$();\n" "}\n" + // TODO(jonskeet): Do we really need merging behaviour like this? "input.ReadMessage($name$_);\n"); // No need to support TYPE_GROUP... } @@ -95,7 +96,7 @@ void MessageFieldGenerator::GenerateSerializationCode(io::Printer* printer) { printer->Print( variables_, "if ($has_property_check$) {\n" - " output.WriteMessage($number$, fieldNames[$field_ordinal$], $property_name$);\n" + " output.WriteMessage($number$, $property_name$);\n" "}\n"); } diff --git a/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc b/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc index f2b66a00..cb7e1b5a 100644 --- a/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc @@ -73,7 +73,6 @@ void PrimitiveFieldGenerator::GenerateMembers(io::Printer* printer) { printer->Print( variables_, " set { $name$_ = value; }\n"); - } else { printer->Print( variables_, @@ -93,14 +92,14 @@ void PrimitiveFieldGenerator::GenerateMergingCode(io::Printer* printer) { void PrimitiveFieldGenerator::GenerateParsingCode(io::Printer* printer) { printer->Print( variables_, - "input.Read$capitalized_type_name$(ref $name$_);\n"); + "$name$_ = input.Read$capitalized_type_name$();\n"); } void PrimitiveFieldGenerator::GenerateSerializationCode(io::Printer* printer) { printer->Print( variables_, "if ($has_property_check$) {\n" - " output.Write$capitalized_type_name$($number$, fieldNames[$field_ordinal$], $property_name$);\n" + " output.Write$capitalized_type_name$($number$, $property_name$);\n" "}\n"); } @@ -169,13 +168,10 @@ void PrimitiveOneofFieldGenerator::WriteToString(io::Printer* printer) { void PrimitiveOneofFieldGenerator::GenerateParsingCode(io::Printer* printer) { // TODO(jonskeet): What if the value we read is the default value for the type? - printer->Print( - variables_, - "$type_name$ value = $default_value$;\n" - "if (input.Read$capitalized_type_name$(ref value)) {\n" - " $oneof_name$_ = value;\n" - " $oneof_name$Case_ = $oneof_property_name$OneofCase.$property_name$;\n" - "}\n"); + printer->Print( + variables_, + "$oneof_name$_ = input.Read$capitalized_type_name$()\n;" + "$oneof_name$Case_ = $oneof_property_name$OneofCase.$property_name$;\n"); } } // namespace csharp diff --git a/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc b/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc index 937d675a..15e92ab9 100644 --- a/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc @@ -76,7 +76,7 @@ void RepeatedEnumFieldGenerator::GenerateMergingCode(io::Printer* printer) { void RepeatedEnumFieldGenerator::GenerateParsingCode(io::Printer* printer) { printer->Print( variables_, - "input.ReadEnumArray<$type_name$>(tag, fieldName, $name$_);\n"); + "input.ReadEnumArray<$type_name$>(tag, $name$_);\n"); } void RepeatedEnumFieldGenerator::GenerateSerializationCode(io::Printer* printer) { @@ -84,7 +84,7 @@ void RepeatedEnumFieldGenerator::GenerateSerializationCode(io::Printer* printer) // The Write* call should make that cheap though - no need to generate it every time. printer->Print( variables_, - "output.Write$packed$EnumArray($number$, fieldNames[$field_ordinal$], $name$_);\n"); + "output.Write$packed$EnumArray($number$, $name$_);\n"); } void RepeatedEnumFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { diff --git a/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc b/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc index 963f841e..6228aa67 100644 --- a/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc @@ -75,7 +75,7 @@ void RepeatedMessageFieldGenerator::GenerateMergingCode(io::Printer* printer) { void RepeatedMessageFieldGenerator::GenerateParsingCode(io::Printer* printer) { printer->Print( variables_, - "input.ReadMessageArray(tag, fieldName, $name$_, $type_name$.Parser);\n"); + "input.ReadMessageArray(tag, $name$_, $type_name$.Parser);\n"); } void RepeatedMessageFieldGenerator::GenerateSerializationCode(io::Printer* printer) { @@ -83,7 +83,7 @@ void RepeatedMessageFieldGenerator::GenerateSerializationCode(io::Printer* print // The Write* call should make that cheap though - no need to generate it every time. printer->Print( variables_, - "output.WriteMessageArray($number$, fieldNames[$field_ordinal$], $name$_);\n"); + "output.WriteMessageArray($number$, $name$_);\n"); } void RepeatedMessageFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { diff --git a/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc b/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc index 0a91c3c6..f62ea09d 100644 --- a/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc @@ -74,7 +74,7 @@ void RepeatedPrimitiveFieldGenerator::GenerateMergingCode(io::Printer* printer) void RepeatedPrimitiveFieldGenerator::GenerateParsingCode(io::Printer* printer) { printer->Print(variables_, - "input.Read$capitalized_type_name$Array(tag, fieldName, $name$_);\n"); + "input.Read$capitalized_type_name$Array(tag, $name$_);\n"); } void RepeatedPrimitiveFieldGenerator::GenerateSerializationCode( @@ -83,10 +83,10 @@ void RepeatedPrimitiveFieldGenerator::GenerateSerializationCode( // The Write* call should make that cheap though - no need to generate it every time. if (descriptor_->is_packed()) { printer->Print(variables_, - "output.WritePacked$capitalized_type_name$Array($number$, fieldNames[$field_ordinal$], $name$_);\n"); + "output.WritePacked$capitalized_type_name$Array($number$, $name$_);\n"); } else { printer->Print(variables_, - "output.Write$capitalized_type_name$Array($number$, fieldNames[$field_ordinal$], $name$_);\n"); + "output.Write$capitalized_type_name$Array($number$, $name$_);\n"); } } -- cgit v1.2.3 From 8fcde2cabd02ffe6ea061e259f67241f277368de Mon Sep 17 00:00:00 2001 From: Jon Skeet Date: Fri, 12 Jun 2015 11:17:07 +0100 Subject: Fix oneof behaviour in the face of default values. --- .../protobuf/compiler/csharp/csharp_primitive_field.cc | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) (limited to 'src/google') diff --git a/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc b/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc index cb7e1b5a..69056790 100644 --- a/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc @@ -137,8 +137,6 @@ PrimitiveOneofFieldGenerator::~PrimitiveOneofFieldGenerator() { } void PrimitiveOneofFieldGenerator::GenerateMembers(io::Printer* printer) { - // TODO(jonskeet): What should foo.OneofIntField = 0; do? Clear the oneof? - // Currently foo.OneOfStringField = null will clear the oneof, but foo.OneOfStringField = "" won't. Ick. AddDeprecatedFlag(printer); printer->Print( variables_, @@ -148,15 +146,14 @@ void PrimitiveOneofFieldGenerator::GenerateMembers(io::Printer* printer) { if (is_value_type) { printer->Print( variables_, - " $oneof_name$_ = value;\n" - " $oneof_name$Case_ = $oneof_property_name$OneofCase.$property_name$;\n"); + " $oneof_name$_ = value;\n"); } else { printer->Print( variables_, - " $oneof_name$_ = value ?? $default_value$;\n" - " $oneof_name$Case_ = value == null ? $oneof_property_name$OneofCase.None : $oneof_property_name$OneofCase.$property_name$;\n"); + " $oneof_name$_ = value ?? $default_value$;\n"); } printer->Print( + " $oneof_name$Case_ = $oneof_property_name$OneofCase.$property_name$;\n" " }\n" "}\n"); } @@ -167,11 +164,9 @@ void PrimitiveOneofFieldGenerator::WriteToString(io::Printer* printer) { } void PrimitiveOneofFieldGenerator::GenerateParsingCode(io::Printer* printer) { - // TODO(jonskeet): What if the value we read is the default value for the type? printer->Print( variables_, - "$oneof_name$_ = input.Read$capitalized_type_name$()\n;" - "$oneof_name$Case_ = $oneof_property_name$OneofCase.$property_name$;\n"); + "$property_name$ = input.Read$capitalized_type_name$()\n;"); } } // namespace csharp -- cgit v1.2.3 From 43527448595b2e19a03747c494d1b33bced6086a Mon Sep 17 00:00:00 2001 From: Jon Skeet Date: Fri, 12 Jun 2015 11:18:37 +0100 Subject: Use Length to check string/bytes fields for emptiness - it's faster than an equality check. --- src/google/protobuf/compiler/csharp/csharp_primitive_field.cc | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'src/google') diff --git a/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc b/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc index 69056790..e48c6ba9 100644 --- a/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc @@ -52,6 +52,10 @@ PrimitiveFieldGenerator::PrimitiveFieldGenerator( // TODO(jonskeet): Make this cleaner... is_value_type = descriptor->type() != FieldDescriptor::TYPE_STRING && descriptor->type() != FieldDescriptor::TYPE_BYTES; + if (!is_value_type) { + variables_["has_property_check"] = variables_["property_name"] + ".Length != 0"; + variables_["other_has_property_check"] = "other." + variables_["property_name"] + ".Length != 0"; + } } PrimitiveFieldGenerator::~PrimitiveFieldGenerator() { @@ -90,9 +94,11 @@ void PrimitiveFieldGenerator::GenerateMergingCode(io::Printer* printer) { } void PrimitiveFieldGenerator::GenerateParsingCode(io::Printer* printer) { + // Note: invoke the property setter rather than writing straight to the field, + // so that we can normalize "null to empty" for strings and bytes. printer->Print( variables_, - "$name$_ = input.Read$capitalized_type_name$();\n"); + "$property_name$ = input.Read$capitalized_type_name$();\n"); } void PrimitiveFieldGenerator::GenerateSerializationCode(io::Printer* printer) { -- cgit v1.2.3 From 1b71db1180953e592e134ddd509f54d6024df593 Mon Sep 17 00:00:00 2001 From: Jon Skeet Date: Fri, 12 Jun 2015 11:19:50 +0100 Subject: Optimization of CalculateSize: avoid foreach over empty lists. --- .../protobuf/compiler/csharp/csharp_repeated_enum_field.cc | 6 +----- .../protobuf/compiler/csharp/csharp_repeated_message_field.cc | 6 ++++-- .../compiler/csharp/csharp_repeated_primitive_field.cc | 10 +++++----- 3 files changed, 10 insertions(+), 12 deletions(-) (limited to 'src/google') diff --git a/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc b/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc index 15e92ab9..3fe5ab21 100644 --- a/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc @@ -89,13 +89,11 @@ void RepeatedEnumFieldGenerator::GenerateSerializationCode(io::Printer* printer) void RepeatedEnumFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { // TODO(jonskeet): Move all this code into CodedOutputStream? It's a lot to repeat everywhere... - printer->Print("{\n"); - printer->Indent(); printer->Print( variables_, - "int dataSize = 0;\n" "if ($name$_.Count > 0) {\n"); printer->Indent(); + printer->Print("int dataSize = 0;\n"); printer->Print( variables_, "foreach ($type_name$ element in $name$_) {\n" @@ -115,8 +113,6 @@ void RepeatedEnumFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer } printer->Outdent(); printer->Print("}\n"); - printer->Outdent(); - printer->Print("}\n"); } void RepeatedEnumFieldGenerator::WriteHash(io::Printer* printer) { diff --git a/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc b/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc index 6228aa67..d7e4d80f 100644 --- a/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc @@ -90,8 +90,10 @@ void RepeatedMessageFieldGenerator::GenerateSerializedSizeCode(io::Printer* prin // TODO(jonskeet): Put this into CodedOutputStream. printer->Print( variables_, - "foreach ($type_name$ element in $name$_) {\n" - " size += pb::CodedOutputStream.ComputeMessageSize($number$, element);\n" + "if ($name$_.Count > 0) {\n" + " foreach ($type_name$ element in $name$_) {\n" + " size += pb::CodedOutputStream.ComputeMessageSize($number$, element);\n" + " }\n" "}\n"); } diff --git a/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc b/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc index f62ea09d..2dd879fe 100644 --- a/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc @@ -93,7 +93,9 @@ void RepeatedPrimitiveFieldGenerator::GenerateSerializationCode( void RepeatedPrimitiveFieldGenerator::GenerateSerializedSizeCode( io::Printer* printer) { // TODO(jonskeet): Do this in the runtime if possible. It's a pain, but it must be feasible... - printer->Print("{\n"); + printer->Print( + "if ($name$_.Count > 0) {\n", + "name", name()); printer->Indent(); printer->Print("int dataSize = 0;\n"); int fixedSize = GetFixedSize(descriptor_->type()); @@ -112,10 +114,8 @@ void RepeatedPrimitiveFieldGenerator::GenerateSerializedSizeCode( int tagSize = internal::WireFormat::TagSize(descriptor_->number(), descriptor_->type()); if (descriptor_->is_packed()) { printer->Print( - "if ($name$_.Count != 0) {\n" - " size += $tag_size$ + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize);\n" - "}\n", - "name", name(), "tag_size", SimpleItoa(tagSize)); + "size += $tag_size$ + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize);\n", + "tag_size", SimpleItoa(tagSize)); } else { printer->Print( "size += $tag_size$ * $name$_.Count;\n", -- cgit v1.2.3 From 5a33827eec75b980fb152c531e4c6b75ce5af015 Mon Sep 17 00:00:00 2001 From: Jon Skeet Date: Fri, 12 Jun 2015 11:52:14 +0100 Subject: Move Count checks into the serialization code I wouldn't expect this to affect anything, but it appears to. --- .../compiler/csharp/csharp_repeated_enum_field.cc | 6 +++--- .../compiler/csharp/csharp_repeated_message_field.cc | 4 +++- .../compiler/csharp/csharp_repeated_primitive_field.cc | 15 ++++++--------- 3 files changed, 12 insertions(+), 13 deletions(-) (limited to 'src/google') diff --git a/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc b/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc index 3fe5ab21..22dec710 100644 --- a/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc @@ -80,11 +80,11 @@ void RepeatedEnumFieldGenerator::GenerateParsingCode(io::Printer* printer) { } void RepeatedEnumFieldGenerator::GenerateSerializationCode(io::Printer* printer) { - // TODO(jonskeet): Originally, this checked for Count > 0 first. - // The Write* call should make that cheap though - no need to generate it every time. printer->Print( variables_, - "output.Write$packed$EnumArray($number$, $name$_);\n"); + "if ($name$_.Count > 0) {\n" + " output.Write$packed$EnumArray($number$, $name$_);\n" + "}\n"); } void RepeatedEnumFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { diff --git a/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc b/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc index d7e4d80f..4b570d3b 100644 --- a/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc @@ -83,7 +83,9 @@ void RepeatedMessageFieldGenerator::GenerateSerializationCode(io::Printer* print // The Write* call should make that cheap though - no need to generate it every time. printer->Print( variables_, - "output.WriteMessageArray($number$, $name$_);\n"); + "if ($name$_.Count > 0) {\n" + " output.WriteMessageArray($number$, $name$_);\n" + "}\n"); } void RepeatedMessageFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { diff --git a/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc b/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc index 2dd879fe..a5457785 100644 --- a/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc @@ -49,6 +49,7 @@ namespace csharp { RepeatedPrimitiveFieldGenerator::RepeatedPrimitiveFieldGenerator( const FieldDescriptor* descriptor, int fieldOrdinal) : FieldGeneratorBase(descriptor, fieldOrdinal) { + variables_["packed"] = descriptor->is_packed() ? "Packed" : ""; } RepeatedPrimitiveFieldGenerator::~RepeatedPrimitiveFieldGenerator() { @@ -79,15 +80,11 @@ void RepeatedPrimitiveFieldGenerator::GenerateParsingCode(io::Printer* printer) void RepeatedPrimitiveFieldGenerator::GenerateSerializationCode( io::Printer* printer) { - // TODO(jonskeet): Originally, this checked for Count > 0 first. - // The Write* call should make that cheap though - no need to generate it every time. - if (descriptor_->is_packed()) { - printer->Print(variables_, - "output.WritePacked$capitalized_type_name$Array($number$, $name$_);\n"); - } else { - printer->Print(variables_, - "output.Write$capitalized_type_name$Array($number$, $name$_);\n"); - } + printer->Print( + variables_, + "if ($name$_.Count > 0) {\n" + " output.Write$packed$$capitalized_type_name$Array($number$, $name$_);\n" + "}\n"); } void RepeatedPrimitiveFieldGenerator::GenerateSerializedSizeCode( -- cgit v1.2.3 From a8dae140c60d9b29c72a7f342ec7081b2116fea9 Mon Sep 17 00:00:00 2001 From: Jon Skeet Date: Fri, 12 Jun 2015 13:11:16 +0100 Subject: Fix oneof generator - forgot to provide variables... --- src/google/protobuf/compiler/csharp/csharp_primitive_field.cc | 1 + 1 file changed, 1 insertion(+) (limited to 'src/google') diff --git a/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc b/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc index e48c6ba9..0164cdca 100644 --- a/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc @@ -159,6 +159,7 @@ void PrimitiveOneofFieldGenerator::GenerateMembers(io::Printer* printer) { " $oneof_name$_ = value ?? $default_value$;\n"); } printer->Print( + variables_, " $oneof_name$Case_ = $oneof_property_name$OneofCase.$property_name$;\n" " }\n" "}\n"); -- cgit v1.2.3 From 828b7e61d0443832d99002fbda12a359e5f9f221 Mon Sep 17 00:00:00 2001 From: Jon Skeet Date: Wed, 17 Jun 2015 14:59:10 +0100 Subject: Use the fact that we know the tag size and bytes at codegen time to optimize. --- csharp/src/AddressBook/Addressbook.cs | 31 +- csharp/src/ProtoMunge/Program.cs | 2 + .../ProtocolBuffers.Test/CodedInputStreamTest.cs | 9 +- .../ProtocolBuffers.Test/CodedOutputStreamTest.cs | 36 +- .../TestProtos/UnittestImportProto3.cs | 5 +- .../TestProtos/UnittestImportPublicProto3.cs | 5 +- .../TestProtos/UnittestIssues.cs | 55 +- .../TestProtos/UnittestProto3.cs | 613 +++++++++++--------- .../CodedOutputStream.ComputeSize.cs | 220 +------- csharp/src/ProtocolBuffers/CodedOutputStream.cs | 617 ++++++--------------- .../DescriptorProtos/DescriptorProtoFile.cs | 458 +++++++++------ .../protobuf/compiler/csharp/csharp_enum_field.cc | 10 +- .../protobuf/compiler/csharp/csharp_field_base.cc | 15 +- .../compiler/csharp/csharp_message_field.cc | 6 +- .../compiler/csharp/csharp_primitive_field.cc | 23 +- .../compiler/csharp/csharp_repeated_enum_field.cc | 22 +- .../csharp/csharp_repeated_message_field.cc | 8 +- .../csharp/csharp_repeated_primitive_field.cc | 21 +- src/google/protobuf/wire_format.h | 2 +- 19 files changed, 970 insertions(+), 1188 deletions(-) (limited to 'src/google') diff --git a/csharp/src/AddressBook/Addressbook.cs b/csharp/src/AddressBook/Addressbook.cs index 4acb8cac..480fb92a 100644 --- a/csharp/src/AddressBook/Addressbook.cs +++ b/csharp/src/AddressBook/Addressbook.cs @@ -139,13 +139,16 @@ namespace Google.ProtocolBuffers.Examples.AddressBook { public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { - output.WriteString(1, Name); + output.WriteRawTag(10); + output.WriteString(Name); } if (Id != 0) { - output.WriteInt32(2, Id); + output.WriteRawTag(16); + output.WriteInt32(Id); } if (Email.Length != 0) { - output.WriteString(3, Email); + output.WriteRawTag(26); + output.WriteString(Email); } if (phone_.Count > 0) { output.WriteMessageArray(4, phone_); @@ -155,18 +158,19 @@ namespace Google.ProtocolBuffers.Examples.AddressBook { public int CalculateSize() { int size = 0; if (Name.Length != 0) { - size += pb::CodedOutputStream.ComputeStringSize(1, Name); + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (Id != 0) { - size += pb::CodedOutputStream.ComputeInt32Size(2, Id); + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Id); } if (Email.Length != 0) { - size += pb::CodedOutputStream.ComputeStringSize(3, Email); + size += 1 + pb::CodedOutputStream.ComputeStringSize(Email); } if (phone_.Count > 0) { foreach (global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber element in phone_) { - size += pb::CodedOutputStream.ComputeMessageSize(4, element); + size += pb::CodedOutputStream.ComputeMessageSize(element); } + size += 1 * phone_.Count; } return size; } @@ -286,20 +290,22 @@ namespace Google.ProtocolBuffers.Examples.AddressBook { public void WriteTo(pb::CodedOutputStream output) { if (Number.Length != 0) { - output.WriteString(1, Number); + output.WriteRawTag(10); + output.WriteString(Number); } if (Type != global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType.HOME) { - output.WriteEnum(2, (int) Type); + output.WriteRawTag(16); + output.WriteEnum((int) Type); } } public int CalculateSize() { int size = 0; if (Number.Length != 0) { - size += pb::CodedOutputStream.ComputeStringSize(1, Number); + size += 1 + pb::CodedOutputStream.ComputeStringSize(Number); } if (Type != global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType.HOME) { - size += pb::CodedOutputStream.ComputeEnumSize(2, (int) Type); + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type); } return size; } @@ -401,8 +407,9 @@ namespace Google.ProtocolBuffers.Examples.AddressBook { int size = 0; if (person_.Count > 0) { foreach (global::Google.ProtocolBuffers.Examples.AddressBook.Person element in person_) { - size += pb::CodedOutputStream.ComputeMessageSize(1, element); + size += pb::CodedOutputStream.ComputeMessageSize(element); } + size += 1 * person_.Count; } return size; } diff --git a/csharp/src/ProtoMunge/Program.cs b/csharp/src/ProtoMunge/Program.cs index 53dc3501..6379f30b 100644 --- a/csharp/src/ProtoMunge/Program.cs +++ b/csharp/src/ProtoMunge/Program.cs @@ -38,6 +38,8 @@ using System; using System.Collections; using System.Collections.Generic; using System.IO; +using Google.Protobuf; +using Google.Protobuf.Descriptors; using Google.ProtocolBuffers.Descriptors; namespace Google.ProtocolBuffers.ProtoMunge diff --git a/csharp/src/ProtocolBuffers.Test/CodedInputStreamTest.cs b/csharp/src/ProtocolBuffers.Test/CodedInputStreamTest.cs index 07f54e94..0baa3a75 100644 --- a/csharp/src/ProtocolBuffers.Test/CodedInputStreamTest.cs +++ b/csharp/src/ProtocolBuffers.Test/CodedInputStreamTest.cs @@ -479,7 +479,8 @@ namespace Google.Protobuf int msgSize = 1 + 1 + arraySize; byte[] bytes = new byte[msgSize]; CodedOutputStream output = CodedOutputStream.CreateInstance(bytes); - output.WritePackedInt32Array(8, new RepeatedField { 0, -1, -2, -3, -4, -5 }); + output.WriteTag(8, WireFormat.WireType.LengthDelimited); + output.WritePackedInt32Array(new RepeatedField { 0, -1, -2, -3, -4, -5 }); Assert.AreEqual(0, output.SpaceLeft); @@ -527,8 +528,10 @@ namespace Google.Protobuf using (var ms = new MemoryStream()) { CodedOutputStream output = CodedOutputStream.CreateInstance(ms); - output.WriteBytes(1, ByteString.CopyFrom(new byte[100])); - output.WriteBytes(2, ByteString.CopyFrom(new byte[100])); + output.WriteTag(1, WireFormat.WireType.LengthDelimited); + output.WriteBytes(ByteString.CopyFrom(new byte[100])); + output.WriteTag(2, WireFormat.WireType.LengthDelimited); + output.WriteBytes(ByteString.CopyFrom(new byte[100])); output.Flush(); ms.Position = 0; diff --git a/csharp/src/ProtocolBuffers.Test/CodedOutputStreamTest.cs b/csharp/src/ProtocolBuffers.Test/CodedOutputStreamTest.cs index 682c005a..bc053e19 100644 --- a/csharp/src/ProtocolBuffers.Test/CodedOutputStreamTest.cs +++ b/csharp/src/ProtocolBuffers.Test/CodedOutputStreamTest.cs @@ -295,12 +295,12 @@ namespace Google.Protobuf [Test] public void TestNegativeEnumNoTag() { - Assert.AreEqual(10, CodedOutputStream.ComputeInt32SizeNoTag(-2)); - Assert.AreEqual(10, CodedOutputStream.ComputeEnumSizeNoTag((int) TestNegEnum.Value)); + Assert.AreEqual(10, CodedOutputStream.ComputeInt32Size(-2)); + Assert.AreEqual(10, CodedOutputStream.ComputeEnumSize((int) TestNegEnum.Value)); byte[] bytes = new byte[10]; CodedOutputStream output = CodedOutputStream.CreateInstance(bytes); - output.WriteEnumNoTag((int) TestNegEnum.Value); + output.WriteEnum((int) TestNegEnum.Value); Assert.AreEqual(0, output.SpaceLeft); Assert.AreEqual("FE-FF-FF-FF-FF-FF-FF-FF-FF-01", BitConverter.ToString(bytes)); @@ -308,21 +308,6 @@ namespace Google.Protobuf enum TestNegEnum { None = 0, Value = -2 } - [Test] - public void TestNegativeEnumWithTag() - { - Assert.AreEqual(11, CodedOutputStream.ComputeInt32Size(8, -2)); - Assert.AreEqual(11, CodedOutputStream.ComputeEnumSize(8, (int) TestNegEnum.Value)); - - byte[] bytes = new byte[11]; - CodedOutputStream output = CodedOutputStream.CreateInstance(bytes); - output.WriteEnum(8, (int) TestNegEnum.Value); - - Assert.AreEqual(0, output.SpaceLeft); - //fyi, 0x40 == 0x08 << 3 + 0, field num + wire format shift - Assert.AreEqual("40-FE-FF-FF-FF-FF-FF-FF-FF-FF-01", BitConverter.ToString(bytes)); - } - [Test] public void TestNegativeEnumArrayPacked() { @@ -330,7 +315,8 @@ namespace Google.Protobuf int msgSize = 1 + 1 + arraySize; byte[] bytes = new byte[msgSize]; CodedOutputStream output = CodedOutputStream.CreateInstance(bytes); - output.WritePackedEnumArray(8, new RepeatedField { + output.WriteTag(8, WireFormat.WireType.LengthDelimited); + output.WritePackedEnumArray(new RepeatedField { 0, (TestNegEnum) (-1), TestNegEnum.Value, (TestNegEnum) (-3), (TestNegEnum) (-4), (TestNegEnum) (-5) }); Assert.AreEqual(0, output.SpaceLeft); @@ -384,17 +370,17 @@ namespace Google.Protobuf // Field 11: numeric value: 500 cout.WriteTag(11, WireFormat.WireType.Varint); Assert.AreEqual(1, cout.Position); - cout.WriteInt32NoTag(500); + cout.WriteInt32(500); Assert.AreEqual(3, cout.Position); //Field 12: length delimited 120 bytes cout.WriteTag(12, WireFormat.WireType.LengthDelimited); Assert.AreEqual(4, cout.Position); - cout.WriteBytesNoTag(ByteString.CopyFrom(content)); + cout.WriteBytes(ByteString.CopyFrom(content)); Assert.AreEqual(115, cout.Position); // Field 13: fixed numeric value: 501 cout.WriteTag(13, WireFormat.WireType.Fixed32); Assert.AreEqual(116, cout.Position); - cout.WriteSFixed32NoTag(501); + cout.WriteSFixed32(501); Assert.AreEqual(120, cout.Position); cout.Flush(); } @@ -405,17 +391,17 @@ namespace Google.Protobuf // Field 1: numeric value: 500 cout.WriteTag(1, WireFormat.WireType.Varint); Assert.AreEqual(1, cout.Position); - cout.WriteInt32NoTag(500); + cout.WriteInt32(500); Assert.AreEqual(3, cout.Position); //Field 2: length delimited 120 bytes cout.WriteTag(2, WireFormat.WireType.LengthDelimited); Assert.AreEqual(4, cout.Position); - cout.WriteBytesNoTag(ByteString.CopyFrom(child)); + cout.WriteBytes(ByteString.CopyFrom(child)); Assert.AreEqual(125, cout.Position); // Field 3: fixed numeric value: 500 cout.WriteTag(3, WireFormat.WireType.Fixed32); Assert.AreEqual(126, cout.Position); - cout.WriteSFixed32NoTag(501); + cout.WriteSFixed32(501); Assert.AreEqual(130, cout.Position); cout.Flush(); } diff --git a/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImportProto3.cs b/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImportProto3.cs index f4bbbc5f..e048f65c 100644 --- a/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImportProto3.cs +++ b/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImportProto3.cs @@ -109,14 +109,15 @@ namespace Google.Protobuf.TestProtos { public void WriteTo(pb::CodedOutputStream output) { if (D != 0) { - output.WriteInt32(1, D); + output.WriteRawTag(8); + output.WriteInt32(D); } } public int CalculateSize() { int size = 0; if (D != 0) { - size += pb::CodedOutputStream.ComputeInt32Size(1, D); + size += 1 + pb::CodedOutputStream.ComputeInt32Size(D); } return size; } diff --git a/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImportPublicProto3.cs b/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImportPublicProto3.cs index a79fa70e..5d9f0b7a 100644 --- a/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImportPublicProto3.cs +++ b/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImportPublicProto3.cs @@ -94,14 +94,15 @@ namespace Google.Protobuf.TestProtos { public void WriteTo(pb::CodedOutputStream output) { if (E != 0) { - output.WriteInt32(1, E); + output.WriteRawTag(8); + output.WriteInt32(E); } } public int CalculateSize() { int size = 0; if (E != 0) { - size += pb::CodedOutputStream.ComputeInt32Size(1, E); + size += 1 + pb::CodedOutputStream.ComputeInt32Size(E); } return size; } diff --git a/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestIssues.cs b/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestIssues.cs index 6e59f205..1ea3728d 100644 --- a/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestIssues.cs +++ b/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestIssues.cs @@ -155,25 +155,27 @@ namespace UnitTest.Issues.TestProtos { public void WriteTo(pb::CodedOutputStream output) { if (Value != global::UnitTest.Issues.TestProtos.NegativeEnum.NEGATIVE_ENUM_ZERO) { - output.WriteEnum(1, (int) Value); + output.WriteRawTag(8); + output.WriteEnum((int) Value); } if (values_.Count > 0) { output.WriteEnumArray(2, values_); } if (packedValues_.Count > 0) { - output.WritePackedEnumArray(3, packedValues_); + output.WriteRawTag(26); + output.WritePackedEnumArray(packedValues_); } } public int CalculateSize() { int size = 0; if (Value != global::UnitTest.Issues.TestProtos.NegativeEnum.NEGATIVE_ENUM_ZERO) { - size += pb::CodedOutputStream.ComputeEnumSize(1, (int) Value); + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Value); } if (values_.Count > 0) { int dataSize = 0; foreach (global::UnitTest.Issues.TestProtos.NegativeEnum element in values_) { - dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag((int) element); + dataSize += pb::CodedOutputStream.ComputeEnumSize((int) element); } size += dataSize; size += 1 * values_.Count; @@ -181,11 +183,10 @@ namespace UnitTest.Issues.TestProtos { if (packedValues_.Count > 0) { int dataSize = 0; foreach (global::UnitTest.Issues.TestProtos.NegativeEnum element in packedValues_) { - dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag((int) element); + dataSize += pb::CodedOutputStream.ComputeEnumSize((int) element); } size += dataSize; - size += 1; - size += pb::CodedOutputStream.ComputeRawVarint32Size((uint) dataSize); + size += 1 + pb::CodedOutputStream.ComputeRawVarint32Size((uint) dataSize); } return size; } @@ -305,7 +306,7 @@ namespace UnitTest.Issues.TestProtos { public static pb::MessageParser Parser { get { return _parser; } } private static readonly string[] _fieldNames = new string[] { "EnumArray", "EnumValue", "MessageArray", "MessageValue", "PrimitiveArray", "PrimitiveValue" }; - private static readonly uint[] _fieldTags = new uint[] { 48, 40, 34, 26, 16, 8 }; + private static readonly uint[] _fieldTags = new uint[] { 50, 40, 34, 26, 18, 8 }; public static pbd::MessageDescriptor Descriptor { get { return global::UnitTest.Issues.TestProtos.UnittestIssues.internal__static_unittest_issues_DeprecatedFieldsMessage__Descriptor; } } @@ -397,57 +398,62 @@ namespace UnitTest.Issues.TestProtos { public void WriteTo(pb::CodedOutputStream output) { if (PrimitiveValue != 0) { - output.WriteInt32(1, PrimitiveValue); + output.WriteRawTag(8); + output.WriteInt32(PrimitiveValue); } if (primitiveArray_.Count > 0) { - output.WritePackedInt32Array(2, primitiveArray_); + output.WriteRawTag(18); + output.WritePackedInt32Array(primitiveArray_); } if (messageValue_ != null) { - output.WriteMessage(3, MessageValue); + output.WriteRawTag(26); + output.WriteMessage(MessageValue); } if (messageArray_.Count > 0) { output.WriteMessageArray(4, messageArray_); } if (EnumValue != global::UnitTest.Issues.TestProtos.DeprecatedEnum.DEPRECATED_ZERO) { - output.WriteEnum(5, (int) EnumValue); + output.WriteRawTag(40); + output.WriteEnum((int) EnumValue); } if (enumArray_.Count > 0) { - output.WritePackedEnumArray(6, enumArray_); + output.WriteRawTag(50); + output.WritePackedEnumArray(enumArray_); } } public int CalculateSize() { int size = 0; if (PrimitiveValue != 0) { - size += pb::CodedOutputStream.ComputeInt32Size(1, PrimitiveValue); + size += 1 + pb::CodedOutputStream.ComputeInt32Size(PrimitiveValue); } if (primitiveArray_.Count > 0) { int dataSize = 0; foreach (int element in primitiveArray_) { - dataSize += pb::CodedOutputStream.ComputeInt32SizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeInt32Size(element); } size += dataSize; - size += 1 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 1 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (messageValue_ != null) { - size += pb::CodedOutputStream.ComputeMessageSize(3, MessageValue); + size += 1 + pb::CodedOutputStream.ComputeMessageSize(MessageValue); } if (messageArray_.Count > 0) { foreach (global::UnitTest.Issues.TestProtos.DeprecatedChild element in messageArray_) { - size += pb::CodedOutputStream.ComputeMessageSize(4, element); + size += pb::CodedOutputStream.ComputeMessageSize(element); } + size += 1 * messageArray_.Count; } if (EnumValue != global::UnitTest.Issues.TestProtos.DeprecatedEnum.DEPRECATED_ZERO) { - size += pb::CodedOutputStream.ComputeEnumSize(5, (int) EnumValue); + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) EnumValue); } if (enumArray_.Count > 0) { int dataSize = 0; foreach (global::UnitTest.Issues.TestProtos.DeprecatedEnum element in enumArray_) { - dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag((int) element); + dataSize += pb::CodedOutputStream.ComputeEnumSize((int) element); } size += dataSize; - size += 1; - size += pb::CodedOutputStream.ComputeRawVarint32Size((uint) dataSize); + size += 1 + pb::CodedOutputStream.ComputeRawVarint32Size((uint) dataSize); } return size; } @@ -568,14 +574,15 @@ namespace UnitTest.Issues.TestProtos { public void WriteTo(pb::CodedOutputStream output) { if (Item != 0) { - output.WriteInt32(1, Item); + output.WriteRawTag(8); + output.WriteInt32(Item); } } public int CalculateSize() { int size = 0; if (Item != 0) { - size += pb::CodedOutputStream.ComputeInt32Size(1, Item); + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Item); } return size; } diff --git a/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestProto3.cs b/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestProto3.cs index 7e731a83..a2c5d5f6 100644 --- a/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestProto3.cs +++ b/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestProto3.cs @@ -407,7 +407,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser Parser { get { return _parser; } } private static readonly string[] _fieldNames = new string[] { "oneof_bytes", "oneof_nested_message", "oneof_string", "oneof_uint32", "repeated_bool", "repeated_bytes", "repeated_double", "repeated_fixed32", "repeated_fixed64", "repeated_float", "repeated_foreign_enum", "repeated_foreign_message", "repeated_import_enum", "repeated_import_message", "repeated_int32", "repeated_int64", "repeated_nested_enum", "repeated_nested_message", "repeated_public_import_message", "repeated_sfixed32", "repeated_sfixed64", "repeated_sint32", "repeated_sint64", "repeated_string", "repeated_uint32", "repeated_uint64", "single_bool", "single_bytes", "single_double", "single_fixed32", "single_fixed64", "single_float", "single_foreign_enum", "single_foreign_message", "single_import_enum", "single_import_message", "single_int32", "single_int64", "single_nested_enum", "single_nested_message", "single_public_import_message", "single_sfixed32", "single_sfixed64", "single_sint32", "single_sint64", "single_string", "single_uint32", "single_uint64" }; - private static readonly uint[] _fieldTags = new uint[] { 914, 898, 906, 888, 344, 362, 337, 301, 305, 333, 416, 394, 424, 402, 248, 256, 408, 386, 434, 317, 321, 280, 288, 354, 264, 272, 104, 122, 97, 61, 65, 93, 176, 154, 184, 162, 8, 16, 168, 146, 210, 77, 81, 40, 48, 114, 24, 32 }; + private static readonly uint[] _fieldTags = new uint[] { 914, 898, 906, 888, 346, 362, 338, 298, 306, 330, 418, 394, 426, 402, 250, 258, 410, 386, 434, 314, 322, 282, 290, 354, 266, 274, 104, 122, 97, 61, 65, 93, 176, 154, 184, 162, 8, 16, 168, 146, 210, 77, 81, 40, 48, 114, 24, 32 }; public static pbd::MessageDescriptor Descriptor { get { return global::Google.Protobuf.TestProtos.UnittestProto3.internal__static_protobuf_unittest_TestAllTypes__Descriptor; } } @@ -890,109 +890,144 @@ namespace Google.Protobuf.TestProtos { public void WriteTo(pb::CodedOutputStream output) { if (SingleInt32 != 0) { - output.WriteInt32(1, SingleInt32); + output.WriteRawTag(8); + output.WriteInt32(SingleInt32); } if (SingleInt64 != 0L) { - output.WriteInt64(2, SingleInt64); + output.WriteRawTag(16); + output.WriteInt64(SingleInt64); } if (SingleUint32 != 0) { - output.WriteUInt32(3, SingleUint32); + output.WriteRawTag(24); + output.WriteUInt32(SingleUint32); } if (SingleUint64 != 0UL) { - output.WriteUInt64(4, SingleUint64); + output.WriteRawTag(32); + output.WriteUInt64(SingleUint64); } if (SingleSint32 != 0) { - output.WriteSInt32(5, SingleSint32); + output.WriteRawTag(40); + output.WriteSInt32(SingleSint32); } if (SingleSint64 != 0L) { - output.WriteSInt64(6, SingleSint64); + output.WriteRawTag(48); + output.WriteSInt64(SingleSint64); } if (SingleFixed32 != 0) { - output.WriteFixed32(7, SingleFixed32); + output.WriteRawTag(61); + output.WriteFixed32(SingleFixed32); } if (SingleFixed64 != 0UL) { - output.WriteFixed64(8, SingleFixed64); + output.WriteRawTag(65); + output.WriteFixed64(SingleFixed64); } if (SingleSfixed32 != 0) { - output.WriteSFixed32(9, SingleSfixed32); + output.WriteRawTag(77); + output.WriteSFixed32(SingleSfixed32); } if (SingleSfixed64 != 0L) { - output.WriteSFixed64(10, SingleSfixed64); + output.WriteRawTag(81); + output.WriteSFixed64(SingleSfixed64); } if (SingleFloat != 0F) { - output.WriteFloat(11, SingleFloat); + output.WriteRawTag(93); + output.WriteFloat(SingleFloat); } if (SingleDouble != 0D) { - output.WriteDouble(12, SingleDouble); + output.WriteRawTag(97); + output.WriteDouble(SingleDouble); } if (SingleBool != false) { - output.WriteBool(13, SingleBool); + output.WriteRawTag(104); + output.WriteBool(SingleBool); } if (SingleString.Length != 0) { - output.WriteString(14, SingleString); + output.WriteRawTag(114); + output.WriteString(SingleString); } if (SingleBytes.Length != 0) { - output.WriteBytes(15, SingleBytes); + output.WriteRawTag(122); + output.WriteBytes(SingleBytes); } if (singleNestedMessage_ != null) { - output.WriteMessage(18, SingleNestedMessage); + output.WriteRawTag(146, 1); + output.WriteMessage(SingleNestedMessage); } if (singleForeignMessage_ != null) { - output.WriteMessage(19, SingleForeignMessage); + output.WriteRawTag(154, 1); + output.WriteMessage(SingleForeignMessage); } if (singleImportMessage_ != null) { - output.WriteMessage(20, SingleImportMessage); + output.WriteRawTag(162, 1); + output.WriteMessage(SingleImportMessage); } if (SingleNestedEnum != global::Google.Protobuf.TestProtos.TestAllTypes.Types.NestedEnum.NESTED_ENUM_UNSPECIFIED) { - output.WriteEnum(21, (int) SingleNestedEnum); + output.WriteRawTag(168, 1); + output.WriteEnum((int) SingleNestedEnum); } if (SingleForeignEnum != global::Google.Protobuf.TestProtos.ForeignEnum.FOREIGN_UNSPECIFIED) { - output.WriteEnum(22, (int) SingleForeignEnum); + output.WriteRawTag(176, 1); + output.WriteEnum((int) SingleForeignEnum); } if (SingleImportEnum != global::Google.Protobuf.TestProtos.ImportEnum.IMPORT_ENUM_UNSPECIFIED) { - output.WriteEnum(23, (int) SingleImportEnum); + output.WriteRawTag(184, 1); + output.WriteEnum((int) SingleImportEnum); } if (singlePublicImportMessage_ != null) { - output.WriteMessage(26, SinglePublicImportMessage); + output.WriteRawTag(210, 1); + output.WriteMessage(SinglePublicImportMessage); } if (repeatedInt32_.Count > 0) { - output.WritePackedInt32Array(31, repeatedInt32_); + output.WriteRawTag(250, 1); + output.WritePackedInt32Array(repeatedInt32_); } if (repeatedInt64_.Count > 0) { - output.WritePackedInt64Array(32, repeatedInt64_); + output.WriteRawTag(130, 2); + output.WritePackedInt64Array(repeatedInt64_); } if (repeatedUint32_.Count > 0) { - output.WritePackedUInt32Array(33, repeatedUint32_); + output.WriteRawTag(138, 2); + output.WritePackedUInt32Array(repeatedUint32_); } if (repeatedUint64_.Count > 0) { - output.WritePackedUInt64Array(34, repeatedUint64_); + output.WriteRawTag(146, 2); + output.WritePackedUInt64Array(repeatedUint64_); } if (repeatedSint32_.Count > 0) { - output.WritePackedSInt32Array(35, repeatedSint32_); + output.WriteRawTag(154, 2); + output.WritePackedSInt32Array(repeatedSint32_); } if (repeatedSint64_.Count > 0) { - output.WritePackedSInt64Array(36, repeatedSint64_); + output.WriteRawTag(162, 2); + output.WritePackedSInt64Array(repeatedSint64_); } if (repeatedFixed32_.Count > 0) { - output.WritePackedFixed32Array(37, repeatedFixed32_); + output.WriteRawTag(170, 2); + output.WritePackedFixed32Array(repeatedFixed32_); } if (repeatedFixed64_.Count > 0) { - output.WritePackedFixed64Array(38, repeatedFixed64_); + output.WriteRawTag(178, 2); + output.WritePackedFixed64Array(repeatedFixed64_); } if (repeatedSfixed32_.Count > 0) { - output.WritePackedSFixed32Array(39, repeatedSfixed32_); + output.WriteRawTag(186, 2); + output.WritePackedSFixed32Array(repeatedSfixed32_); } if (repeatedSfixed64_.Count > 0) { - output.WritePackedSFixed64Array(40, repeatedSfixed64_); + output.WriteRawTag(194, 2); + output.WritePackedSFixed64Array(repeatedSfixed64_); } if (repeatedFloat_.Count > 0) { - output.WritePackedFloatArray(41, repeatedFloat_); + output.WriteRawTag(202, 2); + output.WritePackedFloatArray(repeatedFloat_); } if (repeatedDouble_.Count > 0) { - output.WritePackedDoubleArray(42, repeatedDouble_); + output.WriteRawTag(210, 2); + output.WritePackedDoubleArray(repeatedDouble_); } if (repeatedBool_.Count > 0) { - output.WritePackedBoolArray(43, repeatedBool_); + output.WriteRawTag(218, 2); + output.WritePackedBoolArray(repeatedBool_); } if (repeatedString_.Count > 0) { output.WriteStringArray(44, repeatedString_); @@ -1010,193 +1045,200 @@ namespace Google.Protobuf.TestProtos { output.WriteMessageArray(50, repeatedImportMessage_); } if (repeatedNestedEnum_.Count > 0) { - output.WritePackedEnumArray(51, repeatedNestedEnum_); + output.WriteRawTag(154, 3); + output.WritePackedEnumArray(repeatedNestedEnum_); } if (repeatedForeignEnum_.Count > 0) { - output.WritePackedEnumArray(52, repeatedForeignEnum_); + output.WriteRawTag(162, 3); + output.WritePackedEnumArray(repeatedForeignEnum_); } if (repeatedImportEnum_.Count > 0) { - output.WritePackedEnumArray(53, repeatedImportEnum_); + output.WriteRawTag(170, 3); + output.WritePackedEnumArray(repeatedImportEnum_); } if (repeatedPublicImportMessage_.Count > 0) { output.WriteMessageArray(54, repeatedPublicImportMessage_); } if (oneofFieldCase_ == OneofFieldOneofCase.OneofUint32) { - output.WriteUInt32(111, OneofUint32); + output.WriteRawTag(248, 6); + output.WriteUInt32(OneofUint32); } if (oneofFieldCase_ == OneofFieldOneofCase.OneofNestedMessage) { - output.WriteMessage(112, OneofNestedMessage); + output.WriteRawTag(130, 7); + output.WriteMessage(OneofNestedMessage); } if (oneofFieldCase_ == OneofFieldOneofCase.OneofString) { - output.WriteString(113, OneofString); + output.WriteRawTag(138, 7); + output.WriteString(OneofString); } if (oneofFieldCase_ == OneofFieldOneofCase.OneofBytes) { - output.WriteBytes(114, OneofBytes); + output.WriteRawTag(146, 7); + output.WriteBytes(OneofBytes); } } public int CalculateSize() { int size = 0; if (SingleInt32 != 0) { - size += pb::CodedOutputStream.ComputeInt32Size(1, SingleInt32); + size += 1 + pb::CodedOutputStream.ComputeInt32Size(SingleInt32); } if (SingleInt64 != 0L) { - size += pb::CodedOutputStream.ComputeInt64Size(2, SingleInt64); + size += 1 + pb::CodedOutputStream.ComputeInt64Size(SingleInt64); } if (SingleUint32 != 0) { - size += pb::CodedOutputStream.ComputeUInt32Size(3, SingleUint32); + size += 1 + pb::CodedOutputStream.ComputeUInt32Size(SingleUint32); } if (SingleUint64 != 0UL) { - size += pb::CodedOutputStream.ComputeUInt64Size(4, SingleUint64); + size += 1 + pb::CodedOutputStream.ComputeUInt64Size(SingleUint64); } if (SingleSint32 != 0) { - size += pb::CodedOutputStream.ComputeSInt32Size(5, SingleSint32); + size += 1 + pb::CodedOutputStream.ComputeSInt32Size(SingleSint32); } if (SingleSint64 != 0L) { - size += pb::CodedOutputStream.ComputeSInt64Size(6, SingleSint64); + size += 1 + pb::CodedOutputStream.ComputeSInt64Size(SingleSint64); } if (SingleFixed32 != 0) { - size += pb::CodedOutputStream.ComputeFixed32Size(7, SingleFixed32); + size += 1 + 4; } if (SingleFixed64 != 0UL) { - size += pb::CodedOutputStream.ComputeFixed64Size(8, SingleFixed64); + size += 1 + 8; } if (SingleSfixed32 != 0) { - size += pb::CodedOutputStream.ComputeSFixed32Size(9, SingleSfixed32); + size += 1 + 4; } if (SingleSfixed64 != 0L) { - size += pb::CodedOutputStream.ComputeSFixed64Size(10, SingleSfixed64); + size += 1 + 8; } if (SingleFloat != 0F) { - size += pb::CodedOutputStream.ComputeFloatSize(11, SingleFloat); + size += 1 + 4; } if (SingleDouble != 0D) { - size += pb::CodedOutputStream.ComputeDoubleSize(12, SingleDouble); + size += 1 + 8; } if (SingleBool != false) { - size += pb::CodedOutputStream.ComputeBoolSize(13, SingleBool); + size += 1 + 1; } if (SingleString.Length != 0) { - size += pb::CodedOutputStream.ComputeStringSize(14, SingleString); + size += 1 + pb::CodedOutputStream.ComputeStringSize(SingleString); } if (SingleBytes.Length != 0) { - size += pb::CodedOutputStream.ComputeBytesSize(15, SingleBytes); + size += 1 + pb::CodedOutputStream.ComputeBytesSize(SingleBytes); } if (singleNestedMessage_ != null) { - size += pb::CodedOutputStream.ComputeMessageSize(18, SingleNestedMessage); + size += 2 + pb::CodedOutputStream.ComputeMessageSize(SingleNestedMessage); } if (singleForeignMessage_ != null) { - size += pb::CodedOutputStream.ComputeMessageSize(19, SingleForeignMessage); + size += 2 + pb::CodedOutputStream.ComputeMessageSize(SingleForeignMessage); } if (singleImportMessage_ != null) { - size += pb::CodedOutputStream.ComputeMessageSize(20, SingleImportMessage); + size += 2 + pb::CodedOutputStream.ComputeMessageSize(SingleImportMessage); } if (SingleNestedEnum != global::Google.Protobuf.TestProtos.TestAllTypes.Types.NestedEnum.NESTED_ENUM_UNSPECIFIED) { - size += pb::CodedOutputStream.ComputeEnumSize(21, (int) SingleNestedEnum); + size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) SingleNestedEnum); } if (SingleForeignEnum != global::Google.Protobuf.TestProtos.ForeignEnum.FOREIGN_UNSPECIFIED) { - size += pb::CodedOutputStream.ComputeEnumSize(22, (int) SingleForeignEnum); + size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) SingleForeignEnum); } if (SingleImportEnum != global::Google.Protobuf.TestProtos.ImportEnum.IMPORT_ENUM_UNSPECIFIED) { - size += pb::CodedOutputStream.ComputeEnumSize(23, (int) SingleImportEnum); + size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) SingleImportEnum); } if (singlePublicImportMessage_ != null) { - size += pb::CodedOutputStream.ComputeMessageSize(26, SinglePublicImportMessage); + size += 2 + pb::CodedOutputStream.ComputeMessageSize(SinglePublicImportMessage); } if (repeatedInt32_.Count > 0) { int dataSize = 0; foreach (int element in repeatedInt32_) { - dataSize += pb::CodedOutputStream.ComputeInt32SizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeInt32Size(element); } size += dataSize; - size += 2 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 2 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (repeatedInt64_.Count > 0) { int dataSize = 0; foreach (long element in repeatedInt64_) { - dataSize += pb::CodedOutputStream.ComputeInt64SizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeInt64Size(element); } size += dataSize; - size += 2 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 2 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (repeatedUint32_.Count > 0) { int dataSize = 0; foreach (uint element in repeatedUint32_) { - dataSize += pb::CodedOutputStream.ComputeUInt32SizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeUInt32Size(element); } size += dataSize; - size += 2 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 2 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (repeatedUint64_.Count > 0) { int dataSize = 0; foreach (ulong element in repeatedUint64_) { - dataSize += pb::CodedOutputStream.ComputeUInt64SizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeUInt64Size(element); } size += dataSize; - size += 2 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 2 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (repeatedSint32_.Count > 0) { int dataSize = 0; foreach (int element in repeatedSint32_) { - dataSize += pb::CodedOutputStream.ComputeSInt32SizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeSInt32Size(element); } size += dataSize; - size += 2 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 2 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (repeatedSint64_.Count > 0) { int dataSize = 0; foreach (long element in repeatedSint64_) { - dataSize += pb::CodedOutputStream.ComputeSInt64SizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeSInt64Size(element); } size += dataSize; - size += 2 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 2 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (repeatedFixed32_.Count > 0) { int dataSize = 0; dataSize = 4 * repeatedFixed32_.Count; size += dataSize; - size += 2 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 2 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (repeatedFixed64_.Count > 0) { int dataSize = 0; dataSize = 8 * repeatedFixed64_.Count; size += dataSize; - size += 2 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 2 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (repeatedSfixed32_.Count > 0) { int dataSize = 0; dataSize = 4 * repeatedSfixed32_.Count; size += dataSize; - size += 2 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 2 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (repeatedSfixed64_.Count > 0) { int dataSize = 0; dataSize = 8 * repeatedSfixed64_.Count; size += dataSize; - size += 2 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 2 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (repeatedFloat_.Count > 0) { int dataSize = 0; dataSize = 4 * repeatedFloat_.Count; size += dataSize; - size += 2 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 2 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (repeatedDouble_.Count > 0) { int dataSize = 0; dataSize = 8 * repeatedDouble_.Count; size += dataSize; - size += 2 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 2 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (repeatedBool_.Count > 0) { int dataSize = 0; dataSize = 1 * repeatedBool_.Count; size += dataSize; - size += 2 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 2 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (repeatedString_.Count > 0) { int dataSize = 0; foreach (string element in repeatedString_) { - dataSize += pb::CodedOutputStream.ComputeStringSizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeStringSize(element); } size += dataSize; size += 2 * repeatedString_.Count; @@ -1204,69 +1246,70 @@ namespace Google.Protobuf.TestProtos { if (repeatedBytes_.Count > 0) { int dataSize = 0; foreach (pb::ByteString element in repeatedBytes_) { - dataSize += pb::CodedOutputStream.ComputeBytesSizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeBytesSize(element); } size += dataSize; size += 2 * repeatedBytes_.Count; } if (repeatedNestedMessage_.Count > 0) { foreach (global::Google.Protobuf.TestProtos.TestAllTypes.Types.NestedMessage element in repeatedNestedMessage_) { - size += pb::CodedOutputStream.ComputeMessageSize(48, element); + size += pb::CodedOutputStream.ComputeMessageSize(element); } + size += 2 * repeatedNestedMessage_.Count; } if (repeatedForeignMessage_.Count > 0) { foreach (global::Google.Protobuf.TestProtos.ForeignMessage element in repeatedForeignMessage_) { - size += pb::CodedOutputStream.ComputeMessageSize(49, element); + size += pb::CodedOutputStream.ComputeMessageSize(element); } + size += 2 * repeatedForeignMessage_.Count; } if (repeatedImportMessage_.Count > 0) { foreach (global::Google.Protobuf.TestProtos.ImportMessage element in repeatedImportMessage_) { - size += pb::CodedOutputStream.ComputeMessageSize(50, element); + size += pb::CodedOutputStream.ComputeMessageSize(element); } + size += 2 * repeatedImportMessage_.Count; } if (repeatedNestedEnum_.Count > 0) { int dataSize = 0; foreach (global::Google.Protobuf.TestProtos.TestAllTypes.Types.NestedEnum element in repeatedNestedEnum_) { - dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag((int) element); + dataSize += pb::CodedOutputStream.ComputeEnumSize((int) element); } size += dataSize; - size += 2; - size += pb::CodedOutputStream.ComputeRawVarint32Size((uint) dataSize); + size += 2 + pb::CodedOutputStream.ComputeRawVarint32Size((uint) dataSize); } if (repeatedForeignEnum_.Count > 0) { int dataSize = 0; foreach (global::Google.Protobuf.TestProtos.ForeignEnum element in repeatedForeignEnum_) { - dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag((int) element); + dataSize += pb::CodedOutputStream.ComputeEnumSize((int) element); } size += dataSize; - size += 2; - size += pb::CodedOutputStream.ComputeRawVarint32Size((uint) dataSize); + size += 2 + pb::CodedOutputStream.ComputeRawVarint32Size((uint) dataSize); } if (repeatedImportEnum_.Count > 0) { int dataSize = 0; foreach (global::Google.Protobuf.TestProtos.ImportEnum element in repeatedImportEnum_) { - dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag((int) element); + dataSize += pb::CodedOutputStream.ComputeEnumSize((int) element); } size += dataSize; - size += 2; - size += pb::CodedOutputStream.ComputeRawVarint32Size((uint) dataSize); + size += 2 + pb::CodedOutputStream.ComputeRawVarint32Size((uint) dataSize); } if (repeatedPublicImportMessage_.Count > 0) { foreach (global::Google.Protobuf.TestProtos.PublicImportMessage element in repeatedPublicImportMessage_) { - size += pb::CodedOutputStream.ComputeMessageSize(54, element); + size += pb::CodedOutputStream.ComputeMessageSize(element); } + size += 2 * repeatedPublicImportMessage_.Count; } if (oneofFieldCase_ == OneofFieldOneofCase.OneofUint32) { - size += pb::CodedOutputStream.ComputeUInt32Size(111, OneofUint32); + size += 2 + pb::CodedOutputStream.ComputeUInt32Size(OneofUint32); } if (oneofFieldCase_ == OneofFieldOneofCase.OneofNestedMessage) { - size += pb::CodedOutputStream.ComputeMessageSize(112, OneofNestedMessage); + size += 2 + pb::CodedOutputStream.ComputeMessageSize(OneofNestedMessage); } if (oneofFieldCase_ == OneofFieldOneofCase.OneofString) { - size += pb::CodedOutputStream.ComputeStringSize(113, OneofString); + size += 2 + pb::CodedOutputStream.ComputeStringSize(OneofString); } if (oneofFieldCase_ == OneofFieldOneofCase.OneofBytes) { - size += pb::CodedOutputStream.ComputeBytesSize(114, OneofBytes); + size += 2 + pb::CodedOutputStream.ComputeBytesSize(OneofBytes); } return size; } @@ -1607,8 +1650,8 @@ namespace Google.Protobuf.TestProtos { break; } case 888: { - OneofUint32 = input.ReadUInt32() - ;break; + OneofUint32 = input.ReadUInt32(); + break; } case 898: { global::Google.Protobuf.TestProtos.TestAllTypes.Types.NestedMessage subBuilder = new global::Google.Protobuf.TestProtos.TestAllTypes.Types.NestedMessage(); @@ -1620,12 +1663,12 @@ namespace Google.Protobuf.TestProtos { break; } case 906: { - OneofString = input.ReadString() - ;break; + OneofString = input.ReadString(); + break; } case 914: { - OneofBytes = input.ReadBytes() - ;break; + OneofBytes = input.ReadBytes(); + break; } } } @@ -1692,14 +1735,15 @@ namespace Google.Protobuf.TestProtos { public void WriteTo(pb::CodedOutputStream output) { if (Bb != 0) { - output.WriteInt32(1, Bb); + output.WriteRawTag(8); + output.WriteInt32(Bb); } } public int CalculateSize() { int size = 0; if (Bb != 0) { - size += pb::CodedOutputStream.ComputeInt32Size(1, Bb); + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Bb); } return size; } @@ -1802,10 +1846,12 @@ namespace Google.Protobuf.TestProtos { public void WriteTo(pb::CodedOutputStream output) { if (child_ != null) { - output.WriteMessage(1, Child); + output.WriteRawTag(10); + output.WriteMessage(Child); } if (payload_ != null) { - output.WriteMessage(2, Payload); + output.WriteRawTag(18); + output.WriteMessage(Payload); } if (repeatedChild_.Count > 0) { output.WriteMessageArray(3, repeatedChild_); @@ -1815,15 +1861,16 @@ namespace Google.Protobuf.TestProtos { public int CalculateSize() { int size = 0; if (child_ != null) { - size += pb::CodedOutputStream.ComputeMessageSize(1, Child); + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Child); } if (payload_ != null) { - size += pb::CodedOutputStream.ComputeMessageSize(2, Payload); + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Payload); } if (repeatedChild_.Count > 0) { foreach (global::Google.Protobuf.TestProtos.NestedTestAllTypes element in repeatedChild_) { - size += pb::CodedOutputStream.ComputeMessageSize(3, element); + size += pb::CodedOutputStream.ComputeMessageSize(element); } + size += 1 * repeatedChild_.Count; } return size; } @@ -1932,14 +1979,15 @@ namespace Google.Protobuf.TestProtos { public void WriteTo(pb::CodedOutputStream output) { if (DeprecatedInt32 != 0) { - output.WriteInt32(1, DeprecatedInt32); + output.WriteRawTag(8); + output.WriteInt32(DeprecatedInt32); } } public int CalculateSize() { int size = 0; if (DeprecatedInt32 != 0) { - size += pb::CodedOutputStream.ComputeInt32Size(1, DeprecatedInt32); + size += 1 + pb::CodedOutputStream.ComputeInt32Size(DeprecatedInt32); } return size; } @@ -2023,14 +2071,15 @@ namespace Google.Protobuf.TestProtos { public void WriteTo(pb::CodedOutputStream output) { if (C != 0) { - output.WriteInt32(1, C); + output.WriteRawTag(8); + output.WriteInt32(C); } } public int CalculateSize() { int size = 0; if (C != 0) { - size += pb::CodedOutputStream.ComputeInt32Size(1, C); + size += 1 + pb::CodedOutputStream.ComputeInt32Size(C); } return size; } @@ -2180,14 +2229,15 @@ namespace Google.Protobuf.TestProtos { public void WriteTo(pb::CodedOutputStream output) { if (foreignNested_ != null) { - output.WriteMessage(1, ForeignNested); + output.WriteRawTag(10); + output.WriteMessage(ForeignNested); } } public int CalculateSize() { int size = 0; if (foreignNested_ != null) { - size += pb::CodedOutputStream.ComputeMessageSize(1, ForeignNested); + size += 1 + pb::CodedOutputStream.ComputeMessageSize(ForeignNested); } return size; } @@ -2287,20 +2337,22 @@ namespace Google.Protobuf.TestProtos { public void WriteTo(pb::CodedOutputStream output) { if (A != 0) { - output.WriteInt32(1, A); + output.WriteRawTag(8); + output.WriteInt32(A); } if (Bb != 0) { - output.WriteInt32(268435455, Bb); + output.WriteRawTag(248, 255, 255, 255, 7); + output.WriteInt32(Bb); } } public int CalculateSize() { int size = 0; if (A != 0) { - size += pb::CodedOutputStream.ComputeInt32Size(1, A); + size += 1 + pb::CodedOutputStream.ComputeInt32Size(A); } if (Bb != 0) { - size += pb::CodedOutputStream.ComputeInt32Size(268435455, Bb); + size += 5 + pb::CodedOutputStream.ComputeInt32Size(Bb); } return size; } @@ -2399,20 +2451,22 @@ namespace Google.Protobuf.TestProtos { public void WriteTo(pb::CodedOutputStream output) { if (a_ != null) { - output.WriteMessage(1, A); + output.WriteRawTag(10); + output.WriteMessage(A); } if (I != 0) { - output.WriteInt32(2, I); + output.WriteRawTag(16); + output.WriteInt32(I); } } public int CalculateSize() { int size = 0; if (a_ != null) { - size += pb::CodedOutputStream.ComputeMessageSize(1, A); + size += 1 + pb::CodedOutputStream.ComputeMessageSize(A); } if (I != 0) { - size += pb::CodedOutputStream.ComputeInt32Size(2, I); + size += 1 + pb::CodedOutputStream.ComputeInt32Size(I); } return size; } @@ -2507,14 +2561,15 @@ namespace Google.Protobuf.TestProtos { public void WriteTo(pb::CodedOutputStream output) { if (bb_ != null) { - output.WriteMessage(1, Bb); + output.WriteRawTag(10); + output.WriteMessage(Bb); } } public int CalculateSize() { int size = 0; if (bb_ != null) { - size += pb::CodedOutputStream.ComputeMessageSize(1, Bb); + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Bb); } return size; } @@ -2612,20 +2667,22 @@ namespace Google.Protobuf.TestProtos { public void WriteTo(pb::CodedOutputStream output) { if (a_ != null) { - output.WriteMessage(1, A); + output.WriteRawTag(10); + output.WriteMessage(A); } if (OptionalInt32 != 0) { - output.WriteInt32(2, OptionalInt32); + output.WriteRawTag(16); + output.WriteInt32(OptionalInt32); } } public int CalculateSize() { int size = 0; if (a_ != null) { - size += pb::CodedOutputStream.ComputeMessageSize(1, A); + size += 1 + pb::CodedOutputStream.ComputeMessageSize(A); } if (OptionalInt32 != 0) { - size += pb::CodedOutputStream.ComputeInt32Size(2, OptionalInt32); + size += 1 + pb::CodedOutputStream.ComputeInt32Size(OptionalInt32); } return size; } @@ -2678,7 +2735,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser Parser { get { return _parser; } } private static readonly string[] _fieldNames = new string[] { "EnumField", "MessageField", "PrimitiveField", "RepeatedEnumField", "RepeatedMessageField", "RepeatedPrimitiveField", "RepeatedStringField", "StringField" }; - private static readonly uint[] _fieldTags = new uint[] { 24, 34, 8, 72, 82, 56, 66, 18 }; + private static readonly uint[] _fieldTags = new uint[] { 24, 34, 8, 74, 82, 58, 66, 18 }; public static pbd::MessageDescriptor Descriptor { get { return global::Google.Protobuf.TestProtos.UnittestProto3.internal__static_protobuf_unittest_TestCamelCaseFieldNames__Descriptor; } } @@ -2782,25 +2839,31 @@ namespace Google.Protobuf.TestProtos { public void WriteTo(pb::CodedOutputStream output) { if (PrimitiveField != 0) { - output.WriteInt32(1, PrimitiveField); + output.WriteRawTag(8); + output.WriteInt32(PrimitiveField); } if (StringField.Length != 0) { - output.WriteString(2, StringField); + output.WriteRawTag(18); + output.WriteString(StringField); } if (EnumField != global::Google.Protobuf.TestProtos.ForeignEnum.FOREIGN_UNSPECIFIED) { - output.WriteEnum(3, (int) EnumField); + output.WriteRawTag(24); + output.WriteEnum((int) EnumField); } if (messageField_ != null) { - output.WriteMessage(4, MessageField); + output.WriteRawTag(34); + output.WriteMessage(MessageField); } if (repeatedPrimitiveField_.Count > 0) { - output.WritePackedInt32Array(7, repeatedPrimitiveField_); + output.WriteRawTag(58); + output.WritePackedInt32Array(repeatedPrimitiveField_); } if (repeatedStringField_.Count > 0) { output.WriteStringArray(8, repeatedStringField_); } if (repeatedEnumField_.Count > 0) { - output.WritePackedEnumArray(9, repeatedEnumField_); + output.WriteRawTag(74); + output.WritePackedEnumArray(repeatedEnumField_); } if (repeatedMessageField_.Count > 0) { output.WriteMessageArray(10, repeatedMessageField_); @@ -2810,29 +2873,29 @@ namespace Google.Protobuf.TestProtos { public int CalculateSize() { int size = 0; if (PrimitiveField != 0) { - size += pb::CodedOutputStream.ComputeInt32Size(1, PrimitiveField); + size += 1 + pb::CodedOutputStream.ComputeInt32Size(PrimitiveField); } if (StringField.Length != 0) { - size += pb::CodedOutputStream.ComputeStringSize(2, StringField); + size += 1 + pb::CodedOutputStream.ComputeStringSize(StringField); } if (EnumField != global::Google.Protobuf.TestProtos.ForeignEnum.FOREIGN_UNSPECIFIED) { - size += pb::CodedOutputStream.ComputeEnumSize(3, (int) EnumField); + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) EnumField); } if (messageField_ != null) { - size += pb::CodedOutputStream.ComputeMessageSize(4, MessageField); + size += 1 + pb::CodedOutputStream.ComputeMessageSize(MessageField); } if (repeatedPrimitiveField_.Count > 0) { int dataSize = 0; foreach (int element in repeatedPrimitiveField_) { - dataSize += pb::CodedOutputStream.ComputeInt32SizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeInt32Size(element); } size += dataSize; - size += 1 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 1 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (repeatedStringField_.Count > 0) { int dataSize = 0; foreach (string element in repeatedStringField_) { - dataSize += pb::CodedOutputStream.ComputeStringSizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeStringSize(element); } size += dataSize; size += 1 * repeatedStringField_.Count; @@ -2840,16 +2903,16 @@ namespace Google.Protobuf.TestProtos { if (repeatedEnumField_.Count > 0) { int dataSize = 0; foreach (global::Google.Protobuf.TestProtos.ForeignEnum element in repeatedEnumField_) { - dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag((int) element); + dataSize += pb::CodedOutputStream.ComputeEnumSize((int) element); } size += dataSize; - size += 1; - size += pb::CodedOutputStream.ComputeRawVarint32Size((uint) dataSize); + size += 1 + pb::CodedOutputStream.ComputeRawVarint32Size((uint) dataSize); } if (repeatedMessageField_.Count > 0) { foreach (global::Google.Protobuf.TestProtos.ForeignMessage element in repeatedMessageField_) { - size += pb::CodedOutputStream.ComputeMessageSize(10, element); + size += pb::CodedOutputStream.ComputeMessageSize(element); } + size += 1 * repeatedMessageField_.Count; } return size; } @@ -3010,32 +3073,36 @@ namespace Google.Protobuf.TestProtos { public void WriteTo(pb::CodedOutputStream output) { if (MyInt != 0L) { - output.WriteInt64(1, MyInt); + output.WriteRawTag(8); + output.WriteInt64(MyInt); } if (MyString.Length != 0) { - output.WriteString(11, MyString); + output.WriteRawTag(90); + output.WriteString(MyString); } if (MyFloat != 0F) { - output.WriteFloat(101, MyFloat); + output.WriteRawTag(173, 6); + output.WriteFloat(MyFloat); } if (singleNestedMessage_ != null) { - output.WriteMessage(200, SingleNestedMessage); + output.WriteRawTag(194, 12); + output.WriteMessage(SingleNestedMessage); } } public int CalculateSize() { int size = 0; if (MyString.Length != 0) { - size += pb::CodedOutputStream.ComputeStringSize(11, MyString); + size += 1 + pb::CodedOutputStream.ComputeStringSize(MyString); } if (MyInt != 0L) { - size += pb::CodedOutputStream.ComputeInt64Size(1, MyInt); + size += 1 + pb::CodedOutputStream.ComputeInt64Size(MyInt); } if (MyFloat != 0F) { - size += pb::CodedOutputStream.ComputeFloatSize(101, MyFloat); + size += 2 + 4; } if (singleNestedMessage_ != null) { - size += pb::CodedOutputStream.ComputeMessageSize(200, SingleNestedMessage); + size += 2 + pb::CodedOutputStream.ComputeMessageSize(SingleNestedMessage); } return size; } @@ -3157,20 +3224,22 @@ namespace Google.Protobuf.TestProtos { public void WriteTo(pb::CodedOutputStream output) { if (Bb != 0) { - output.WriteInt32(1, Bb); + output.WriteRawTag(8); + output.WriteInt32(Bb); } if (Oo != 0L) { - output.WriteInt64(2, Oo); + output.WriteRawTag(16); + output.WriteInt64(Oo); } } public int CalculateSize() { int size = 0; if (Oo != 0L) { - size += pb::CodedOutputStream.ComputeInt64Size(2, Oo); + size += 1 + pb::CodedOutputStream.ComputeInt64Size(Oo); } if (Bb != 0) { - size += pb::CodedOutputStream.ComputeInt32Size(1, Bb); + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Bb); } return size; } @@ -3266,14 +3335,15 @@ namespace Google.Protobuf.TestProtos { public void WriteTo(pb::CodedOutputStream output) { if (SparseEnum != global::Google.Protobuf.TestProtos.TestSparseEnum.TEST_SPARSE_ENUM_UNSPECIFIED) { - output.WriteEnum(1, (int) SparseEnum); + output.WriteRawTag(8); + output.WriteEnum((int) SparseEnum); } } public int CalculateSize() { int size = 0; if (SparseEnum != global::Google.Protobuf.TestProtos.TestSparseEnum.TEST_SPARSE_ENUM_UNSPECIFIED) { - size += pb::CodedOutputStream.ComputeEnumSize(1, (int) SparseEnum); + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) SparseEnum); } return size; } @@ -3357,14 +3427,15 @@ namespace Google.Protobuf.TestProtos { public void WriteTo(pb::CodedOutputStream output) { if (Data.Length != 0) { - output.WriteString(1, Data); + output.WriteRawTag(10); + output.WriteString(Data); } } public int CalculateSize() { int size = 0; if (Data.Length != 0) { - size += pb::CodedOutputStream.ComputeStringSize(1, Data); + size += 1 + pb::CodedOutputStream.ComputeStringSize(Data); } return size; } @@ -3455,7 +3526,7 @@ namespace Google.Protobuf.TestProtos { if (data_.Count > 0) { int dataSize = 0; foreach (string element in data_) { - dataSize += pb::CodedOutputStream.ComputeStringSizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeStringSize(element); } size += dataSize; size += 1 * data_.Count; @@ -3540,14 +3611,15 @@ namespace Google.Protobuf.TestProtos { public void WriteTo(pb::CodedOutputStream output) { if (Data.Length != 0) { - output.WriteBytes(1, Data); + output.WriteRawTag(10); + output.WriteBytes(Data); } } public int CalculateSize() { int size = 0; if (Data.Length != 0) { - size += pb::CodedOutputStream.ComputeBytesSize(1, Data); + size += 1 + pb::CodedOutputStream.ComputeBytesSize(Data); } return size; } @@ -3631,14 +3703,15 @@ namespace Google.Protobuf.TestProtos { public void WriteTo(pb::CodedOutputStream output) { if (Data.Length != 0) { - output.WriteBytes(1, Data); + output.WriteRawTag(10); + output.WriteBytes(Data); } } public int CalculateSize() { int size = 0; if (Data.Length != 0) { - size += pb::CodedOutputStream.ComputeBytesSize(1, Data); + size += 1 + pb::CodedOutputStream.ComputeBytesSize(Data); } return size; } @@ -3722,14 +3795,15 @@ namespace Google.Protobuf.TestProtos { public void WriteTo(pb::CodedOutputStream output) { if (Data != 0) { - output.WriteInt32(1, Data); + output.WriteRawTag(8); + output.WriteInt32(Data); } } public int CalculateSize() { int size = 0; if (Data != 0) { - size += pb::CodedOutputStream.ComputeInt32Size(1, Data); + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Data); } return size; } @@ -3813,14 +3887,15 @@ namespace Google.Protobuf.TestProtos { public void WriteTo(pb::CodedOutputStream output) { if (Data != 0) { - output.WriteUInt32(1, Data); + output.WriteRawTag(8); + output.WriteUInt32(Data); } } public int CalculateSize() { int size = 0; if (Data != 0) { - size += pb::CodedOutputStream.ComputeUInt32Size(1, Data); + size += 1 + pb::CodedOutputStream.ComputeUInt32Size(Data); } return size; } @@ -3904,14 +3979,15 @@ namespace Google.Protobuf.TestProtos { public void WriteTo(pb::CodedOutputStream output) { if (Data != 0L) { - output.WriteInt64(1, Data); + output.WriteRawTag(8); + output.WriteInt64(Data); } } public int CalculateSize() { int size = 0; if (Data != 0L) { - size += pb::CodedOutputStream.ComputeInt64Size(1, Data); + size += 1 + pb::CodedOutputStream.ComputeInt64Size(Data); } return size; } @@ -3995,14 +4071,15 @@ namespace Google.Protobuf.TestProtos { public void WriteTo(pb::CodedOutputStream output) { if (Data != 0UL) { - output.WriteUInt64(1, Data); + output.WriteRawTag(8); + output.WriteUInt64(Data); } } public int CalculateSize() { int size = 0; if (Data != 0UL) { - size += pb::CodedOutputStream.ComputeUInt64Size(1, Data); + size += 1 + pb::CodedOutputStream.ComputeUInt64Size(Data); } return size; } @@ -4086,14 +4163,15 @@ namespace Google.Protobuf.TestProtos { public void WriteTo(pb::CodedOutputStream output) { if (Data != false) { - output.WriteBool(1, Data); + output.WriteRawTag(8); + output.WriteBool(Data); } } public int CalculateSize() { int size = 0; if (Data != false) { - size += pb::CodedOutputStream.ComputeBoolSize(1, Data); + size += 1 + 1; } return size; } @@ -4216,26 +4294,29 @@ namespace Google.Protobuf.TestProtos { public void WriteTo(pb::CodedOutputStream output) { if (fooCase_ == FooOneofCase.FooInt) { - output.WriteInt32(1, FooInt); + output.WriteRawTag(8); + output.WriteInt32(FooInt); } if (fooCase_ == FooOneofCase.FooString) { - output.WriteString(2, FooString); + output.WriteRawTag(18); + output.WriteString(FooString); } if (fooCase_ == FooOneofCase.FooMessage) { - output.WriteMessage(3, FooMessage); + output.WriteRawTag(26); + output.WriteMessage(FooMessage); } } public int CalculateSize() { int size = 0; if (fooCase_ == FooOneofCase.FooInt) { - size += pb::CodedOutputStream.ComputeInt32Size(1, FooInt); + size += 1 + pb::CodedOutputStream.ComputeInt32Size(FooInt); } if (fooCase_ == FooOneofCase.FooString) { - size += pb::CodedOutputStream.ComputeStringSize(2, FooString); + size += 1 + pb::CodedOutputStream.ComputeStringSize(FooString); } if (fooCase_ == FooOneofCase.FooMessage) { - size += pb::CodedOutputStream.ComputeMessageSize(3, FooMessage); + size += 1 + pb::CodedOutputStream.ComputeMessageSize(FooMessage); } return size; } @@ -4269,12 +4350,12 @@ namespace Google.Protobuf.TestProtos { } break; case 8: { - FooInt = input.ReadInt32() - ;break; + FooInt = input.ReadInt32(); + break; } case 18: { - FooString = input.ReadString() - ;break; + FooString = input.ReadString(); + break; } case 26: { global::Google.Protobuf.TestProtos.TestAllTypes subBuilder = new global::Google.Protobuf.TestProtos.TestAllTypes(); @@ -4443,46 +4524,60 @@ namespace Google.Protobuf.TestProtos { public void WriteTo(pb::CodedOutputStream output) { if (packedInt32_.Count > 0) { - output.WritePackedInt32Array(90, packedInt32_); + output.WriteRawTag(210, 5); + output.WritePackedInt32Array(packedInt32_); } if (packedInt64_.Count > 0) { - output.WritePackedInt64Array(91, packedInt64_); + output.WriteRawTag(218, 5); + output.WritePackedInt64Array(packedInt64_); } if (packedUint32_.Count > 0) { - output.WritePackedUInt32Array(92, packedUint32_); + output.WriteRawTag(226, 5); + output.WritePackedUInt32Array(packedUint32_); } if (packedUint64_.Count > 0) { - output.WritePackedUInt64Array(93, packedUint64_); + output.WriteRawTag(234, 5); + output.WritePackedUInt64Array(packedUint64_); } if (packedSint32_.Count > 0) { - output.WritePackedSInt32Array(94, packedSint32_); + output.WriteRawTag(242, 5); + output.WritePackedSInt32Array(packedSint32_); } if (packedSint64_.Count > 0) { - output.WritePackedSInt64Array(95, packedSint64_); + output.WriteRawTag(250, 5); + output.WritePackedSInt64Array(packedSint64_); } if (packedFixed32_.Count > 0) { - output.WritePackedFixed32Array(96, packedFixed32_); + output.WriteRawTag(130, 6); + output.WritePackedFixed32Array(packedFixed32_); } if (packedFixed64_.Count > 0) { - output.WritePackedFixed64Array(97, packedFixed64_); + output.WriteRawTag(138, 6); + output.WritePackedFixed64Array(packedFixed64_); } if (packedSfixed32_.Count > 0) { - output.WritePackedSFixed32Array(98, packedSfixed32_); + output.WriteRawTag(146, 6); + output.WritePackedSFixed32Array(packedSfixed32_); } if (packedSfixed64_.Count > 0) { - output.WritePackedSFixed64Array(99, packedSfixed64_); + output.WriteRawTag(154, 6); + output.WritePackedSFixed64Array(packedSfixed64_); } if (packedFloat_.Count > 0) { - output.WritePackedFloatArray(100, packedFloat_); + output.WriteRawTag(162, 6); + output.WritePackedFloatArray(packedFloat_); } if (packedDouble_.Count > 0) { - output.WritePackedDoubleArray(101, packedDouble_); + output.WriteRawTag(170, 6); + output.WritePackedDoubleArray(packedDouble_); } if (packedBool_.Count > 0) { - output.WritePackedBoolArray(102, packedBool_); + output.WriteRawTag(178, 6); + output.WritePackedBoolArray(packedBool_); } if (packedEnum_.Count > 0) { - output.WritePackedEnumArray(103, packedEnum_); + output.WriteRawTag(186, 6); + output.WritePackedEnumArray(packedEnum_); } } @@ -4491,101 +4586,100 @@ namespace Google.Protobuf.TestProtos { if (packedInt32_.Count > 0) { int dataSize = 0; foreach (int element in packedInt32_) { - dataSize += pb::CodedOutputStream.ComputeInt32SizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeInt32Size(element); } size += dataSize; - size += 2 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 2 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (packedInt64_.Count > 0) { int dataSize = 0; foreach (long element in packedInt64_) { - dataSize += pb::CodedOutputStream.ComputeInt64SizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeInt64Size(element); } size += dataSize; - size += 2 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 2 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (packedUint32_.Count > 0) { int dataSize = 0; foreach (uint element in packedUint32_) { - dataSize += pb::CodedOutputStream.ComputeUInt32SizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeUInt32Size(element); } size += dataSize; - size += 2 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 2 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (packedUint64_.Count > 0) { int dataSize = 0; foreach (ulong element in packedUint64_) { - dataSize += pb::CodedOutputStream.ComputeUInt64SizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeUInt64Size(element); } size += dataSize; - size += 2 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 2 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (packedSint32_.Count > 0) { int dataSize = 0; foreach (int element in packedSint32_) { - dataSize += pb::CodedOutputStream.ComputeSInt32SizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeSInt32Size(element); } size += dataSize; - size += 2 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 2 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (packedSint64_.Count > 0) { int dataSize = 0; foreach (long element in packedSint64_) { - dataSize += pb::CodedOutputStream.ComputeSInt64SizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeSInt64Size(element); } size += dataSize; - size += 2 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 2 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (packedFixed32_.Count > 0) { int dataSize = 0; dataSize = 4 * packedFixed32_.Count; size += dataSize; - size += 2 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 2 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (packedFixed64_.Count > 0) { int dataSize = 0; dataSize = 8 * packedFixed64_.Count; size += dataSize; - size += 2 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 2 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (packedSfixed32_.Count > 0) { int dataSize = 0; dataSize = 4 * packedSfixed32_.Count; size += dataSize; - size += 2 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 2 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (packedSfixed64_.Count > 0) { int dataSize = 0; dataSize = 8 * packedSfixed64_.Count; size += dataSize; - size += 2 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 2 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (packedFloat_.Count > 0) { int dataSize = 0; dataSize = 4 * packedFloat_.Count; size += dataSize; - size += 2 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 2 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (packedDouble_.Count > 0) { int dataSize = 0; dataSize = 8 * packedDouble_.Count; size += dataSize; - size += 2 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 2 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (packedBool_.Count > 0) { int dataSize = 0; dataSize = 1 * packedBool_.Count; size += dataSize; - size += 2 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 2 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (packedEnum_.Count > 0) { int dataSize = 0; foreach (global::Google.Protobuf.TestProtos.ForeignEnum element in packedEnum_) { - dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag((int) element); + dataSize += pb::CodedOutputStream.ComputeEnumSize((int) element); } size += dataSize; - size += 2; - size += pb::CodedOutputStream.ComputeRawVarint32Size((uint) dataSize); + size += 2 + pb::CodedOutputStream.ComputeRawVarint32Size((uint) dataSize); } return size; } @@ -4896,7 +4990,7 @@ namespace Google.Protobuf.TestProtos { if (unpackedInt32_.Count > 0) { int dataSize = 0; foreach (int element in unpackedInt32_) { - dataSize += pb::CodedOutputStream.ComputeInt32SizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeInt32Size(element); } size += dataSize; size += 2 * unpackedInt32_.Count; @@ -4904,7 +4998,7 @@ namespace Google.Protobuf.TestProtos { if (unpackedInt64_.Count > 0) { int dataSize = 0; foreach (long element in unpackedInt64_) { - dataSize += pb::CodedOutputStream.ComputeInt64SizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeInt64Size(element); } size += dataSize; size += 2 * unpackedInt64_.Count; @@ -4912,7 +5006,7 @@ namespace Google.Protobuf.TestProtos { if (unpackedUint32_.Count > 0) { int dataSize = 0; foreach (uint element in unpackedUint32_) { - dataSize += pb::CodedOutputStream.ComputeUInt32SizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeUInt32Size(element); } size += dataSize; size += 2 * unpackedUint32_.Count; @@ -4920,7 +5014,7 @@ namespace Google.Protobuf.TestProtos { if (unpackedUint64_.Count > 0) { int dataSize = 0; foreach (ulong element in unpackedUint64_) { - dataSize += pb::CodedOutputStream.ComputeUInt64SizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeUInt64Size(element); } size += dataSize; size += 2 * unpackedUint64_.Count; @@ -4928,7 +5022,7 @@ namespace Google.Protobuf.TestProtos { if (unpackedSint32_.Count > 0) { int dataSize = 0; foreach (int element in unpackedSint32_) { - dataSize += pb::CodedOutputStream.ComputeSInt32SizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeSInt32Size(element); } size += dataSize; size += 2 * unpackedSint32_.Count; @@ -4936,7 +5030,7 @@ namespace Google.Protobuf.TestProtos { if (unpackedSint64_.Count > 0) { int dataSize = 0; foreach (long element in unpackedSint64_) { - dataSize += pb::CodedOutputStream.ComputeSInt64SizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeSInt64Size(element); } size += dataSize; size += 2 * unpackedSint64_.Count; @@ -4986,7 +5080,7 @@ namespace Google.Protobuf.TestProtos { if (unpackedEnum_.Count > 0) { int dataSize = 0; foreach (global::Google.Protobuf.TestProtos.ForeignEnum element in unpackedEnum_) { - dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag((int) element); + dataSize += pb::CodedOutputStream.ComputeEnumSize((int) element); } size += dataSize; size += 2 * unpackedEnum_.Count; @@ -5106,7 +5200,7 @@ namespace Google.Protobuf.TestProtos { public static pb::MessageParser Parser { get { return _parser; } } private static readonly string[] _fieldNames = new string[] { "repeated_fixed32", "repeated_fixed64", "repeated_float", "repeated_int32", "repeated_int64", "repeated_uint64" }; - private static readonly uint[] _fieldTags = new uint[] { 101, 16369, 2097141, 104, 16376, 2097144 }; + private static readonly uint[] _fieldTags = new uint[] { 98, 16370, 2097138, 106, 16378, 2097146 }; public static pbd::MessageDescriptor Descriptor { get { return global::Google.Protobuf.TestProtos.UnittestProto3.internal__static_protobuf_unittest_TestRepeatedScalarDifferentTagSizes__Descriptor; } } @@ -5188,22 +5282,28 @@ namespace Google.Protobuf.TestProtos { public void WriteTo(pb::CodedOutputStream output) { if (repeatedFixed32_.Count > 0) { - output.WritePackedFixed32Array(12, repeatedFixed32_); + output.WriteRawTag(98); + output.WritePackedFixed32Array(repeatedFixed32_); } if (repeatedInt32_.Count > 0) { - output.WritePackedInt32Array(13, repeatedInt32_); + output.WriteRawTag(106); + output.WritePackedInt32Array(repeatedInt32_); } if (repeatedFixed64_.Count > 0) { - output.WritePackedFixed64Array(2046, repeatedFixed64_); + output.WriteRawTag(242, 127); + output.WritePackedFixed64Array(repeatedFixed64_); } if (repeatedInt64_.Count > 0) { - output.WritePackedInt64Array(2047, repeatedInt64_); + output.WriteRawTag(250, 127); + output.WritePackedInt64Array(repeatedInt64_); } if (repeatedFloat_.Count > 0) { - output.WritePackedFloatArray(262142, repeatedFloat_); + output.WriteRawTag(242, 255, 127); + output.WritePackedFloatArray(repeatedFloat_); } if (repeatedUint64_.Count > 0) { - output.WritePackedUInt64Array(262143, repeatedUint64_); + output.WriteRawTag(250, 255, 127); + output.WritePackedUInt64Array(repeatedUint64_); } } @@ -5213,43 +5313,43 @@ namespace Google.Protobuf.TestProtos { int dataSize = 0; dataSize = 4 * repeatedFixed32_.Count; size += dataSize; - size += 1 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 1 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (repeatedInt32_.Count > 0) { int dataSize = 0; foreach (int element in repeatedInt32_) { - dataSize += pb::CodedOutputStream.ComputeInt32SizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeInt32Size(element); } size += dataSize; - size += 1 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 1 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (repeatedFixed64_.Count > 0) { int dataSize = 0; dataSize = 8 * repeatedFixed64_.Count; size += dataSize; - size += 2 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 2 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (repeatedInt64_.Count > 0) { int dataSize = 0; foreach (long element in repeatedInt64_) { - dataSize += pb::CodedOutputStream.ComputeInt64SizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeInt64Size(element); } size += dataSize; - size += 2 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 2 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (repeatedFloat_.Count > 0) { int dataSize = 0; dataSize = 4 * repeatedFloat_.Count; size += dataSize; - size += 3 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 3 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (repeatedUint64_.Count > 0) { int dataSize = 0; foreach (ulong element in repeatedUint64_) { - dataSize += pb::CodedOutputStream.ComputeUInt64SizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeUInt64Size(element); } size += dataSize; - size += 3 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 3 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } return size; } @@ -5362,14 +5462,15 @@ namespace Google.Protobuf.TestProtos { public void WriteTo(pb::CodedOutputStream output) { if (A.Length != 0) { - output.WriteString(1, A); + output.WriteRawTag(10); + output.WriteString(A); } } public int CalculateSize() { int size = 0; if (A.Length != 0) { - size += pb::CodedOutputStream.ComputeStringSize(1, A); + size += 1 + pb::CodedOutputStream.ComputeStringSize(A); } return size; } diff --git a/csharp/src/ProtocolBuffers/CodedOutputStream.ComputeSize.cs b/csharp/src/ProtocolBuffers/CodedOutputStream.ComputeSize.cs index aba5a1a2..e3d2b068 100644 --- a/csharp/src/ProtocolBuffers/CodedOutputStream.ComputeSize.cs +++ b/csharp/src/ProtocolBuffers/CodedOutputStream.ComputeSize.cs @@ -47,193 +47,13 @@ namespace Google.Protobuf public sealed partial class CodedOutputStream { private const int LittleEndian64Size = 8; - private const int LittleEndian32Size = 4; + private const int LittleEndian32Size = 4; /// /// Compute the number of bytes that would be needed to encode a /// double field, including the tag. /// - public static int ComputeDoubleSize(int fieldNumber, double value) - { - return ComputeTagSize(fieldNumber) + LittleEndian64Size; - } - - /// - /// Compute the number of bytes that would be needed to encode a - /// float field, including the tag. - /// - public static int ComputeFloatSize(int fieldNumber, float value) - { - return ComputeTagSize(fieldNumber) + LittleEndian32Size; - } - - /// - /// Compute the number of bytes that would be needed to encode a - /// uint64 field, including the tag. - /// - public static int ComputeUInt64Size(int fieldNumber, ulong value) - { - return ComputeTagSize(fieldNumber) + ComputeRawVarint64Size(value); - } - - /// - /// Compute the number of bytes that would be needed to encode an - /// int64 field, including the tag. - /// - public static int ComputeInt64Size(int fieldNumber, long value) - { - return ComputeTagSize(fieldNumber) + ComputeRawVarint64Size((ulong) value); - } - - /// - /// Compute the number of bytes that would be needed to encode an - /// int32 field, including the tag. - /// - public static int ComputeInt32Size(int fieldNumber, int value) - { - return ComputeTagSize(fieldNumber) + ComputeInt32SizeNoTag(value); - } - - /// - /// Compute the number of bytes that would be needed to encode a - /// fixed64 field, including the tag. - /// - public static int ComputeFixed64Size(int fieldNumber, ulong value) - { - return ComputeTagSize(fieldNumber) + LittleEndian64Size; - } - - /// - /// Compute the number of bytes that would be needed to encode a - /// fixed32 field, including the tag. - /// - public static int ComputeFixed32Size(int fieldNumber, uint value) - { - return ComputeTagSize(fieldNumber) + LittleEndian32Size; - } - - /// - /// Compute the number of bytes that would be needed to encode a - /// bool field, including the tag. - /// - public static int ComputeBoolSize(int fieldNumber, bool value) - { - return ComputeTagSize(fieldNumber) + 1; - } - - /// - /// Compute the number of bytes that would be needed to encode a - /// string field, including the tag. - /// - public static int ComputeStringSize(int fieldNumber, String value) - { - int byteArraySize = UTF8.GetByteCount(value); - return ComputeTagSize(fieldNumber) + - ComputeRawVarint32Size((uint) byteArraySize) + - byteArraySize; - } - - /// - /// Compute the number of bytes that would be needed to encode a - /// group field, including the tag. - /// - public static int ComputeGroupSize(int fieldNumber, IMessage value) - { - return ComputeTagSize(fieldNumber)*2 + value.CalculateSize(); - } - - /// - /// Compute the number of bytes that would be needed to encode a - /// group field represented by an UnknownFieldSet, including the tag. - /// - [Obsolete] - public static int ComputeUnknownGroupSize(int fieldNumber, - IMessage value) - { - return ComputeTagSize(fieldNumber)*2 + value.CalculateSize(); - } - - /// - /// Compute the number of bytes that would be needed to encode an - /// embedded message field, including the tag. - /// - public static int ComputeMessageSize(int fieldNumber, IMessage value) - { - int size = value.CalculateSize(); - return ComputeTagSize(fieldNumber) + ComputeRawVarint32Size((uint) size) + size; - } - - /// - /// Compute the number of bytes that would be needed to encode a - /// bytes field, including the tag. - /// - public static int ComputeBytesSize(int fieldNumber, ByteString value) - { - return ComputeTagSize(fieldNumber) + - ComputeRawVarint32Size((uint) value.Length) + - value.Length; - } - - /// - /// Compute the number of bytes that would be needed to encode a - /// uint32 field, including the tag. - /// - public static int ComputeUInt32Size(int fieldNumber, uint value) - { - return ComputeTagSize(fieldNumber) + ComputeRawVarint32Size(value); - } - - /// - /// Compute the number of bytes that would be needed to encode a - /// enum field, including the tag. The caller is responsible for - /// converting the enum value to its numeric value. - /// - public static int ComputeEnumSize(int fieldNumber, int value) - { - return ComputeTagSize(fieldNumber) + ComputeEnumSizeNoTag(value); - } - - /// - /// Compute the number of bytes that would be needed to encode an - /// sfixed32 field, including the tag. - /// - public static int ComputeSFixed32Size(int fieldNumber, int value) - { - return ComputeTagSize(fieldNumber) + LittleEndian32Size; - } - - /// - /// Compute the number of bytes that would be needed to encode an - /// sfixed64 field, including the tag. - /// - public static int ComputeSFixed64Size(int fieldNumber, long value) - { - return ComputeTagSize(fieldNumber) + LittleEndian64Size; - } - - /// - /// Compute the number of bytes that would be needed to encode an - /// sint32 field, including the tag. - /// - public static int ComputeSInt32Size(int fieldNumber, int value) - { - return ComputeTagSize(fieldNumber) + ComputeRawVarint32Size(EncodeZigZag32(value)); - } - - /// - /// Compute the number of bytes that would be needed to encode an - /// sint64 field, including the tag. - /// - public static int ComputeSInt64Size(int fieldNumber, long value) - { - return ComputeTagSize(fieldNumber) + ComputeRawVarint64Size(EncodeZigZag64(value)); - } - - /// - /// Compute the number of bytes that would be needed to encode a - /// double field, including the tag. - /// - public static int ComputeDoubleSizeNoTag(double value) + public static int ComputeDoubleSize(double value) { return LittleEndian64Size; } @@ -242,7 +62,7 @@ namespace Google.Protobuf /// Compute the number of bytes that would be needed to encode a /// float field, including the tag. /// - public static int ComputeFloatSizeNoTag(float value) + public static int ComputeFloatSize(float value) { return LittleEndian32Size; } @@ -251,7 +71,7 @@ namespace Google.Protobuf /// Compute the number of bytes that would be needed to encode a /// uint64 field, including the tag. /// - public static int ComputeUInt64SizeNoTag(ulong value) + public static int ComputeUInt64Size(ulong value) { return ComputeRawVarint64Size(value); } @@ -260,7 +80,7 @@ namespace Google.Protobuf /// Compute the number of bytes that would be needed to encode an /// int64 field, including the tag. /// - public static int ComputeInt64SizeNoTag(long value) + public static int ComputeInt64Size(long value) { return ComputeRawVarint64Size((ulong) value); } @@ -269,7 +89,7 @@ namespace Google.Protobuf /// Compute the number of bytes that would be needed to encode an /// int32 field, including the tag. /// - public static int ComputeInt32SizeNoTag(int value) + public static int ComputeInt32Size(int value) { if (value >= 0) { @@ -286,7 +106,7 @@ namespace Google.Protobuf /// Compute the number of bytes that would be needed to encode a /// fixed64 field, including the tag. /// - public static int ComputeFixed64SizeNoTag(ulong value) + public static int ComputeFixed64Size(ulong value) { return LittleEndian64Size; } @@ -295,7 +115,7 @@ namespace Google.Protobuf /// Compute the number of bytes that would be needed to encode a /// fixed32 field, including the tag. /// - public static int ComputeFixed32SizeNoTag(uint value) + public static int ComputeFixed32Size(uint value) { return LittleEndian32Size; } @@ -304,7 +124,7 @@ namespace Google.Protobuf /// Compute the number of bytes that would be needed to encode a /// bool field, including the tag. /// - public static int ComputeBoolSizeNoTag(bool value) + public static int ComputeBoolSize(bool value) { return 1; } @@ -313,7 +133,7 @@ namespace Google.Protobuf /// Compute the number of bytes that would be needed to encode a /// string field, including the tag. /// - public static int ComputeStringSizeNoTag(String value) + public static int ComputeStringSize(String value) { int byteArraySize = UTF8.GetByteCount(value); return ComputeRawVarint32Size((uint) byteArraySize) + @@ -324,7 +144,7 @@ namespace Google.Protobuf /// Compute the number of bytes that would be needed to encode a /// group field, including the tag. /// - public static int ComputeGroupSizeNoTag(IMessage value) + public static int ComputeGroupSize(IMessage value) { return value.CalculateSize(); } @@ -333,7 +153,7 @@ namespace Google.Protobuf /// Compute the number of bytes that would be needed to encode an /// embedded message field, including the tag. /// - public static int ComputeMessageSizeNoTag(IMessage value) + public static int ComputeMessageSize(IMessage value) { int size = value.CalculateSize(); return ComputeRawVarint32Size((uint) size) + size; @@ -343,7 +163,7 @@ namespace Google.Protobuf /// Compute the number of bytes that would be needed to encode a /// bytes field, including the tag. /// - public static int ComputeBytesSizeNoTag(ByteString value) + public static int ComputeBytesSize(ByteString value) { return ComputeRawVarint32Size((uint) value.Length) + value.Length; @@ -353,7 +173,7 @@ namespace Google.Protobuf /// Compute the number of bytes that would be needed to encode a /// uint32 field, including the tag. /// - public static int ComputeUInt32SizeNoTag(uint value) + public static int ComputeUInt32Size(uint value) { return ComputeRawVarint32Size(value); } @@ -363,17 +183,17 @@ namespace Google.Protobuf /// enum field, including the tag. The caller is responsible for /// converting the enum value to its numeric value. /// - public static int ComputeEnumSizeNoTag(int value) + public static int ComputeEnumSize(int value) { // Currently just a pass-through, but it's nice to separate it logically. - return ComputeInt32SizeNoTag(value); + return ComputeInt32Size(value); } /// /// Compute the number of bytes that would be needed to encode an /// sfixed32 field, including the tag. /// - public static int ComputeSFixed32SizeNoTag(int value) + public static int ComputeSFixed32Size(int value) { return LittleEndian32Size; } @@ -382,7 +202,7 @@ namespace Google.Protobuf /// Compute the number of bytes that would be needed to encode an /// sfixed64 field, including the tag. /// - public static int ComputeSFixed64SizeNoTag(long value) + public static int ComputeSFixed64Size(long value) { return LittleEndian64Size; } @@ -391,7 +211,7 @@ namespace Google.Protobuf /// Compute the number of bytes that would be needed to encode an /// sint32 field, including the tag. /// - public static int ComputeSInt32SizeNoTag(int value) + public static int ComputeSInt32Size(int value) { return ComputeRawVarint32Size(EncodeZigZag32(value)); } @@ -400,7 +220,7 @@ namespace Google.Protobuf /// Compute the number of bytes that would be needed to encode an /// sint64 field, including the tag. /// - public static int ComputeSInt64SizeNoTag(long value) + public static int ComputeSInt64Size(long value) { return ComputeRawVarint64Size(EncodeZigZag64(value)); } diff --git a/csharp/src/ProtocolBuffers/CodedOutputStream.cs b/csharp/src/ProtocolBuffers/CodedOutputStream.cs index bc3ed7d7..6c135e86 100644 --- a/csharp/src/ProtocolBuffers/CodedOutputStream.cs +++ b/csharp/src/ProtocolBuffers/CodedOutputStream.cs @@ -143,248 +143,12 @@ namespace Google.Protobuf } } - #region Writing of tags and fields - /// - /// Writes a double field value, including tag, to the stream. - /// - public void WriteDouble(int fieldNumber, double value) - { - WriteTag(fieldNumber, WireFormat.WireType.Fixed64); - WriteDoubleNoTag(value); - } - - /// - /// Writes a float field value, including tag, to the stream. - /// - public void WriteFloat(int fieldNumber, float value) - { - WriteTag(fieldNumber, WireFormat.WireType.Fixed32); - WriteFloatNoTag(value); - } - - /// - /// Writes a uint64 field value, including tag, to the stream. - /// - public void WriteUInt64(int fieldNumber, ulong value) - { - WriteTag(fieldNumber, WireFormat.WireType.Varint); - WriteRawVarint64(value); - } - - /// - /// Writes an int64 field value, including tag, to the stream. - /// - public void WriteInt64(int fieldNumber, long value) - { - WriteTag(fieldNumber, WireFormat.WireType.Varint); - WriteRawVarint64((ulong) value); - } - - /// - /// Writes an int32 field value, including tag, to the stream. - /// - public void WriteInt32(int fieldNumber, int value) - { - WriteTag(fieldNumber, WireFormat.WireType.Varint); - if (value >= 0) - { - WriteRawVarint32((uint) value); - } - else - { - // Must sign-extend. - WriteRawVarint64((ulong) value); - } - } - - /// - /// Writes a fixed64 field value, including tag, to the stream. - /// - public void WriteFixed64(int fieldNumber, ulong value) - { - WriteTag(fieldNumber, WireFormat.WireType.Fixed64); - WriteRawLittleEndian64(value); - } - - /// - /// Writes a fixed32 field value, including tag, to the stream. - /// - public void WriteFixed32(int fieldNumber, uint value) - { - WriteTag(fieldNumber, WireFormat.WireType.Fixed32); - WriteRawLittleEndian32(value); - } - - /// - /// Writes a bool field value, including tag, to the stream. - /// - public void WriteBool(int fieldNumber, bool value) - { - WriteTag(fieldNumber, WireFormat.WireType.Varint); - WriteRawByte(value ? (byte) 1 : (byte) 0); - } - - /// - /// Writes a string field value, including tag, to the stream. - /// - public void WriteString(int fieldNumber, string value) - { - WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited); - // Optimise the case where we have enough space to write - // the string directly to the buffer, which should be common. - int length = UTF8.GetByteCount(value); - WriteRawVarint32((uint) length); - if (limit - position >= length) - { - if (length == value.Length) // Must be all ASCII... - { - for (int i = 0; i < length; i++) - { - buffer[position + i] = (byte)value[i]; - } - } - else - { - UTF8.GetBytes(value, 0, value.Length, buffer, position); - } - position += length; - } - else - { - byte[] bytes = UTF8.GetBytes(value); - WriteRawBytes(bytes); - } - } - - /// - /// Writes a group field value, including tag, to the stream. - /// - public void WriteGroup(int fieldNumber, IMessage value) - { - WriteTag(fieldNumber, WireFormat.WireType.StartGroup); - value.WriteTo(this); - WriteTag(fieldNumber, WireFormat.WireType.EndGroup); - } - - public void WriteMessage(int fieldNumber, IMessage value) - { - WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited); - WriteRawVarint32((uint) value.CalculateSize()); - value.WriteTo(this); - } - - public void WriteBytes(int fieldNumber, ByteString value) - { - WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited); - WriteRawVarint32((uint) value.Length); - value.WriteRawBytesTo(this); - } - - public void WriteUInt32(int fieldNumber, uint value) - { - WriteTag(fieldNumber, WireFormat.WireType.Varint); - WriteRawVarint32(value); - } - - public void WriteEnum(int fieldNumber, int value) - { - // Currently just a pass-through, but it's nice to separate it logically from WriteInt32. - WriteTag(fieldNumber, WireFormat.WireType.Varint); - WriteInt32NoTag(value); - } - - public void WriteSFixed32(int fieldNumber, int value) - { - WriteTag(fieldNumber, WireFormat.WireType.Fixed32); - WriteRawLittleEndian32((uint) value); - } - - public void WriteSFixed64(int fieldNumber, long value) - { - WriteTag(fieldNumber, WireFormat.WireType.Fixed64); - WriteRawLittleEndian64((ulong) value); - } - - public void WriteSInt32(int fieldNumber, int value) - { - WriteTag(fieldNumber, WireFormat.WireType.Varint); - WriteRawVarint32(EncodeZigZag32(value)); - } - - public void WriteSInt64(int fieldNumber, long value) - { - WriteTag(fieldNumber, WireFormat.WireType.Varint); - WriteRawVarint64(EncodeZigZag64(value)); - } - #endregion - #region Writing of values without tags - // TODO(jonskeet): Remove this? - public void WriteFieldNoTag(FieldType fieldType, object value) - { - switch (fieldType) - { - case FieldType.String: - WriteStringNoTag((string) value); - break; - case FieldType.Message: - WriteMessageNoTag((IMessage) value); - break; - case FieldType.Group: - WriteGroupNoTag((IMessage) value); - break; - case FieldType.Bytes: - WriteBytesNoTag((ByteString) value); - break; - case FieldType.Bool: - WriteBoolNoTag((bool) value); - break; - case FieldType.Enum: - WriteEnumNoTag((int) value); - break; - case FieldType.Int32: - WriteInt32NoTag((int) value); - break; - case FieldType.Int64: - WriteInt64NoTag((long) value); - break; - case FieldType.UInt32: - WriteUInt32NoTag((uint) value); - break; - case FieldType.UInt64: - WriteUInt64NoTag((ulong) value); - break; - case FieldType.SInt32: - WriteSInt32NoTag((int) value); - break; - case FieldType.SInt64: - WriteSInt64NoTag((long) value); - break; - case FieldType.Fixed32: - WriteFixed32NoTag((uint) value); - break; - case FieldType.Fixed64: - WriteFixed64NoTag((ulong) value); - break; - case FieldType.SFixed32: - WriteSFixed32NoTag((int) value); - break; - case FieldType.SFixed64: - WriteSFixed64NoTag((long) value); - break; - case FieldType.Double: - WriteDoubleNoTag((double) value); - break; - case FieldType.Float: - WriteFloatNoTag((float) value); - break; - } - } /// /// Writes a double field value, including tag, to the stream. /// - public void WriteDoubleNoTag(double value) + public void WriteDouble(double value) { WriteRawLittleEndian64((ulong)FrameworkPortability.DoubleToInt64(value)); } @@ -392,7 +156,7 @@ namespace Google.Protobuf /// /// Writes a float field value, without a tag, to the stream. /// - public void WriteFloatNoTag(float value) + public void WriteFloat(float value) { byte[] rawBytes = BitConverter.GetBytes(value); if (!BitConverter.IsLittleEndian) @@ -416,7 +180,7 @@ namespace Google.Protobuf /// /// Writes a uint64 field value, without a tag, to the stream. /// - public void WriteUInt64NoTag(ulong value) + public void WriteUInt64(ulong value) { WriteRawVarint64(value); } @@ -424,7 +188,7 @@ namespace Google.Protobuf /// /// Writes an int64 field value, without a tag, to the stream. /// - public void WriteInt64NoTag(long value) + public void WriteInt64(long value) { WriteRawVarint64((ulong) value); } @@ -432,7 +196,7 @@ namespace Google.Protobuf /// /// Writes an int32 field value, without a tag, to the stream. /// - public void WriteInt32NoTag(int value) + public void WriteInt32(int value) { if (value >= 0) { @@ -448,7 +212,7 @@ namespace Google.Protobuf /// /// Writes a fixed64 field value, without a tag, to the stream. /// - public void WriteFixed64NoTag(ulong value) + public void WriteFixed64(ulong value) { WriteRawLittleEndian64(value); } @@ -456,7 +220,7 @@ namespace Google.Protobuf /// /// Writes a fixed32 field value, without a tag, to the stream. /// - public void WriteFixed32NoTag(uint value) + public void WriteFixed32(uint value) { WriteRawLittleEndian32(value); } @@ -464,7 +228,7 @@ namespace Google.Protobuf /// /// Writes a bool field value, without a tag, to the stream. /// - public void WriteBoolNoTag(bool value) + public void WriteBool(bool value) { WriteRawByte(value ? (byte) 1 : (byte) 0); } @@ -472,485 +236,440 @@ namespace Google.Protobuf /// /// Writes a string field value, without a tag, to the stream. /// - public void WriteStringNoTag(string value) + public void WriteString(string value) { // Optimise the case where we have enough space to write // the string directly to the buffer, which should be common. - int length = Encoding.UTF8.GetByteCount(value); - WriteRawVarint32((uint) length); + int length = UTF8.GetByteCount(value); + WriteRawVarint32((uint)length); if (limit - position >= length) { - Encoding.UTF8.GetBytes(value, 0, value.Length, buffer, position); + if (length == value.Length) // Must be all ASCII... + { + for (int i = 0; i < length; i++) + { + buffer[position + i] = (byte)value[i]; + } + } + else + { + UTF8.GetBytes(value, 0, value.Length, buffer, position); + } position += length; } else { - byte[] bytes = Encoding.UTF8.GetBytes(value); + byte[] bytes = UTF8.GetBytes(value); WriteRawBytes(bytes); } } - /// - /// Writes a group field value, without a tag, to the stream. - /// - public void WriteGroupNoTag(IMessage value) - { - value.WriteTo(this); - } - - public void WriteMessageNoTag(IMessage value) + public void WriteMessage(IMessage value) { WriteRawVarint32((uint) value.CalculateSize()); value.WriteTo(this); } - public void WriteBytesNoTag(ByteString value) + public void WriteBytes(ByteString value) { WriteRawVarint32((uint) value.Length); value.WriteRawBytesTo(this); } - public void WriteUInt32NoTag(uint value) + public void WriteUInt32(uint value) { WriteRawVarint32(value); } - public void WriteEnumNoTag(int value) + public void WriteEnum(int value) { - WriteInt32NoTag(value); + WriteInt32(value); } - public void WriteSFixed32NoTag(int value) + public void WriteSFixed32(int value) { WriteRawLittleEndian32((uint) value); } - public void WriteSFixed64NoTag(long value) + public void WriteSFixed64(long value) { WriteRawLittleEndian64((ulong) value); } - public void WriteSInt32NoTag(int value) + public void WriteSInt32(int value) { WriteRawVarint32(EncodeZigZag32(value)); } - public void WriteSInt64NoTag(long value) + public void WriteSInt64(long value) { WriteRawVarint64(EncodeZigZag64(value)); } #endregion - #region Write array members + #region Write array members, with fields. public void WriteMessageArray(int fieldNumber, RepeatedField list) where T : IMessage { - if (list.Count == 0) - { - return; - } foreach (T value in list) { - WriteMessage(fieldNumber, value); + WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited); + WriteMessage(value); } } public void WriteStringArray(int fieldNumber, RepeatedField list) { - if (list.Count == 0) - { - return; - } foreach (var value in list) { - WriteString(fieldNumber, value); + WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited); + WriteString(value); } } public void WriteBytesArray(int fieldNumber, RepeatedField list) { - if (list.Count == 0) - { - return; - } foreach (var value in list) { - WriteBytes(fieldNumber, value); + WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited); + WriteBytes(value); } } public void WriteBoolArray(int fieldNumber, RepeatedField list) { - if (list.Count == 0) - { - return; - } foreach (var value in list) { - WriteBool(fieldNumber, value); + WriteTag(fieldNumber, WireFormat.WireType.Varint); + WriteBool(value); } } public void WriteInt32Array(int fieldNumber, RepeatedField list) { - if (list.Count == 0) - { - return; - } foreach (var value in list) { - WriteInt32(fieldNumber, value); + WriteTag(fieldNumber, WireFormat.WireType.Varint); + WriteInt32(value); } } public void WriteSInt32Array(int fieldNumber, RepeatedField list) { - if (list.Count == 0) - { - return; - } foreach (var value in list) { - WriteSInt32(fieldNumber, value); + WriteTag(fieldNumber, WireFormat.WireType.Varint); + WriteSInt32(value); } } public void WriteUInt32Array(int fieldNumber, RepeatedField list) { - if (list.Count == 0) - { - return; - } foreach (var value in list) { - WriteUInt32(fieldNumber, value); + WriteTag(fieldNumber, WireFormat.WireType.Varint); + WriteUInt32(value); } } public void WriteFixed32Array(int fieldNumber, RepeatedField list) { - if (list.Count == 0) - { - return; - } foreach (var value in list) { - WriteFixed32(fieldNumber, value); + WriteTag(fieldNumber, WireFormat.WireType.Fixed32); + WriteFixed32(value); } } public void WriteSFixed32Array(int fieldNumber, RepeatedField list) { - if (list.Count == 0) - { - return; - } foreach (var value in list) { - WriteSFixed32(fieldNumber, value); + WriteTag(fieldNumber, WireFormat.WireType.Fixed32); + WriteSFixed32(value); } } public void WriteInt64Array(int fieldNumber, RepeatedField list) { - if (list.Count == 0) - { - return; - } foreach (var value in list) { - WriteInt64(fieldNumber, value); + WriteTag(fieldNumber, WireFormat.WireType.Fixed64); + WriteInt64(value); } } public void WriteSInt64Array(int fieldNumber, RepeatedField list) { - if (list.Count == 0) - { - return; - } foreach (var value in list) { - WriteSInt64(fieldNumber, value); + WriteTag(fieldNumber, WireFormat.WireType.Varint); + WriteSInt64(value); } } public void WriteUInt64Array(int fieldNumber, RepeatedField list) { - if (list.Count == 0) - { - return; - } foreach (var value in list) { - WriteUInt64(fieldNumber, value); + WriteTag(fieldNumber, WireFormat.WireType.Varint); + WriteUInt64(value); } } public void WriteFixed64Array(int fieldNumber, RepeatedField list) { - if (list.Count == 0) - { - return; - } foreach (var value in list) { - WriteFixed64(fieldNumber, value); + WriteTag(fieldNumber, WireFormat.WireType.Fixed64); + WriteFixed64(value); } } public void WriteSFixed64Array(int fieldNumber, RepeatedField list) { - if (list.Count == 0) - { - return; - } foreach (var value in list) { - WriteSFixed64(fieldNumber, value); + WriteTag(fieldNumber, WireFormat.WireType.Fixed64); + WriteSFixed64(value); } } public void WriteDoubleArray(int fieldNumber, RepeatedField list) { - if (list.Count == 0) - { - return; - } foreach (var value in list) { - WriteDouble(fieldNumber, value); + WriteTag(fieldNumber, WireFormat.WireType.Fixed64); + WriteDouble(value); } } public void WriteFloatArray(int fieldNumber, RepeatedField list) { - if (list.Count == 0) - { - return; - } foreach (var value in list) { - WriteFloat(fieldNumber, value); + WriteTag(fieldNumber, WireFormat.WireType.Fixed32); + WriteFloat(value); } } public void WriteEnumArray(int fieldNumber, RepeatedField list) where T : struct, IComparable, IFormattable { - if (list.Count == 0) - { - return; - } // Bit of a hack, to access the values as ints var iterator = list.GetInt32Enumerator(); while (iterator.MoveNext()) { - WriteEnum(fieldNumber, iterator.Current); + WriteTag(fieldNumber, WireFormat.WireType.Varint); + WriteEnum(iterator.Current); } } #endregion + #region Raw tag writing + /// + /// Encodes and writes a tag. + /// + public void WriteTag(int fieldNumber, WireFormat.WireType type) + { + WriteRawVarint32(WireFormat.MakeTag(fieldNumber, type)); + } + + /// + /// Writes the given single-byte tag directly to the stream. + /// + public void WriteRawTag(byte b1) + { + WriteRawByte(b1); + } + + /// + /// Writes the given two-byte tag directly to the stream. + /// + public void WriteRawTag(byte b1, byte b2) + { + WriteRawByte(b1); + WriteRawByte(b2); + } + + /// + /// Writes the given three-byte tag directly to the stream. + /// + public void WriteRawTag(byte b1, byte b2, byte b3) + { + WriteRawByte(b1); + WriteRawByte(b2); + WriteRawByte(b3); + } + + /// + /// Writes the given four-byte tag directly to the stream. + /// + public void WriteRawTag(byte b1, byte b2, byte b3, byte b4) + { + WriteRawByte(b1); + WriteRawByte(b2); + WriteRawByte(b3); + WriteRawByte(b4); + } + + /// + /// Writes the given five-byte tag directly to the stream. + /// + public void WriteRawTag(byte b1, byte b2, byte b3, byte b4, byte b5) + { + WriteRawByte(b1); + WriteRawByte(b2); + WriteRawByte(b3); + WriteRawByte(b4); + WriteRawByte(b5); + } + #endregion + #region Write packed array members // TODO(jonskeet): A lot of these are really inefficient, due to method group conversions. Fix! - public void WritePackedBoolArray(int fieldNumber, RepeatedField list) + // (Alternatively, add extension methods to RepeatedField, accepting the Write* methods via delegates too.) + public void WritePackedBoolArray(RepeatedField list) { - if (list.Count == 0) - { - return; - } uint size = (uint)list.Count; - WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited); WriteRawVarint32(size); foreach (var value in list) { - WriteBoolNoTag(value); + WriteBool(value); } } - public void WritePackedInt32Array(int fieldNumber, RepeatedField list) + public void WritePackedInt32Array(RepeatedField list) { - if (list.Count == 0) - { - return; - } - uint size = list.CalculateSize(ComputeInt32SizeNoTag); - WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited); + uint size = list.CalculateSize(ComputeInt32Size); WriteRawVarint32(size); foreach (var value in list) { - WriteInt32NoTag(value); + WriteInt32(value); } } - public void WritePackedSInt32Array(int fieldNumber, RepeatedField list) + public void WritePackedSInt32Array(RepeatedField list) { - if (list.Count == 0) - { - return; - } - uint size = list.CalculateSize(ComputeSInt32SizeNoTag); - WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited); + uint size = list.CalculateSize(ComputeSInt32Size); WriteRawVarint32(size); foreach (var value in list) { - WriteSInt32NoTag(value); + WriteSInt32(value); } } - public void WritePackedUInt32Array(int fieldNumber, RepeatedField list) + public void WritePackedUInt32Array(RepeatedField list) { - if (list.Count == 0) - { - return; - } - uint size = list.CalculateSize(ComputeUInt32SizeNoTag); - WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited); + uint size = list.CalculateSize(ComputeUInt32Size); WriteRawVarint32(size); foreach (var value in list) { - WriteUInt32NoTag(value); + WriteUInt32(value); } } - public void WritePackedFixed32Array(int fieldNumber, RepeatedField list) + public void WritePackedFixed32Array(RepeatedField list) { - if (list.Count == 0) - { - return; - } uint size = (uint) list.Count * 4; - WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited); WriteRawVarint32(size); foreach (var value in list) { - WriteFixed32NoTag(value); + WriteFixed32(value); } } - public void WritePackedSFixed32Array(int fieldNumber, RepeatedField list) + public void WritePackedSFixed32Array(RepeatedField list) { - if (list.Count == 0) - { - return; - } uint size = (uint) list.Count * 4; - WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited); WriteRawVarint32(size); foreach (var value in list) { - WriteSFixed32NoTag(value); + WriteSFixed32(value); } } - public void WritePackedInt64Array(int fieldNumber, RepeatedField list) + public void WritePackedInt64Array(RepeatedField list) { - if (list.Count == 0) - { - return; - } - uint size = list.CalculateSize(ComputeInt64SizeNoTag); - WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited); + uint size = list.CalculateSize(ComputeInt64Size); WriteRawVarint32(size); foreach (var value in list) { - WriteInt64NoTag(value); + WriteInt64(value); } } - public void WritePackedSInt64Array(int fieldNumber, RepeatedField list) + public void WritePackedSInt64Array(RepeatedField list) { - if (list.Count == 0) - { - return; - } - uint size = list.CalculateSize(ComputeSInt64SizeNoTag); - WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited); + uint size = list.CalculateSize(ComputeSInt64Size); WriteRawVarint32(size); foreach (var value in list) { - WriteSInt64NoTag(value); + WriteSInt64(value); } } - public void WritePackedUInt64Array(int fieldNumber, RepeatedField list) + public void WritePackedUInt64Array(RepeatedField list) { if (list.Count == 0) { return; } - uint size = list.CalculateSize(ComputeUInt64SizeNoTag); - WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited); + uint size = list.CalculateSize(ComputeUInt64Size); WriteRawVarint32(size); foreach (var value in list) { - WriteUInt64NoTag(value); + WriteUInt64(value); } } - public void WritePackedFixed64Array(int fieldNumber, RepeatedField list) + public void WritePackedFixed64Array(RepeatedField list) { - if (list.Count == 0) - { - return; - } uint size = (uint) list.Count * 8; - WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited); WriteRawVarint32(size); foreach (var value in list) { - WriteFixed64NoTag(value); + WriteFixed64(value); } } - public void WritePackedSFixed64Array(int fieldNumber, RepeatedField list) + public void WritePackedSFixed64Array(RepeatedField list) { - if (list.Count == 0) - { - return; - } uint size = (uint) list.Count * 8; - WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited); WriteRawVarint32(size); foreach (var value in list) { - WriteSFixed64NoTag(value); + WriteSFixed64(value); } } - public void WritePackedDoubleArray(int fieldNumber, RepeatedField list) + public void WritePackedDoubleArray(RepeatedField list) { - if (list.Count == 0) - { - return; - } uint size = (uint) list.Count * 8; - WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited); WriteRawVarint32(size); foreach (var value in list) { - WriteDoubleNoTag(value); + WriteDouble(value); } } - public void WritePackedFloatArray(int fieldNumber, RepeatedField list) + public void WritePackedFloatArray(RepeatedField list) { if (list.Count == 0) { return; } uint size = (uint) list.Count * 4; - WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited); WriteRawVarint32(size); foreach (var value in list) { - WriteFloatNoTag(value); + WriteFloat(value); } } - public void WritePackedEnumArray(int fieldNumber, RepeatedField list) + public void WritePackedEnumArray(RepeatedField list) where T : struct, IComparable, IFormattable { if (list.Count == 0) @@ -962,29 +681,19 @@ namespace Google.Protobuf uint size = 0; while (iterator.MoveNext()) { - size += (uint) ComputeEnumSizeNoTag(iterator.Current); + size += (uint) ComputeEnumSize(iterator.Current); } iterator.Reset(); - WriteTag(fieldNumber, WireFormat.WireType.LengthDelimited); WriteRawVarint32(size); while (iterator.MoveNext()) { - WriteEnumNoTag(iterator.Current); + WriteEnum(iterator.Current); } } #endregion #region Underlying writing primitives - - /// - /// Encodes and writes a tag. - /// - public void WriteTag(int fieldNumber, WireFormat.WireType type) - { - WriteRawVarint32(WireFormat.MakeTag(fieldNumber, type)); - } - /// /// Writes a 32 bit value as a varint. The fast route is taken when /// there's enough buffer space left to whizz through without checking diff --git a/csharp/src/ProtocolBuffers/DescriptorProtos/DescriptorProtoFile.cs b/csharp/src/ProtocolBuffers/DescriptorProtos/DescriptorProtoFile.cs index 9a10d6ae..44e6e2e9 100644 --- a/csharp/src/ProtocolBuffers/DescriptorProtos/DescriptorProtoFile.cs +++ b/csharp/src/ProtocolBuffers/DescriptorProtos/DescriptorProtoFile.cs @@ -333,8 +333,9 @@ namespace Google.Protobuf.DescriptorProtos { int size = 0; if (file_.Count > 0) { foreach (global::Google.Protobuf.DescriptorProtos.FileDescriptorProto element in file_) { - size += pb::CodedOutputStream.ComputeMessageSize(1, element); + size += pb::CodedOutputStream.ComputeMessageSize(element); } + size += 1 * file_.Count; } return size; } @@ -508,10 +509,12 @@ namespace Google.Protobuf.DescriptorProtos { public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { - output.WriteString(1, Name); + output.WriteRawTag(10); + output.WriteString(Name); } if (Package.Length != 0) { - output.WriteString(2, Package); + output.WriteRawTag(18); + output.WriteString(Package); } if (dependency_.Count > 0) { output.WriteStringArray(3, dependency_); @@ -529,10 +532,12 @@ namespace Google.Protobuf.DescriptorProtos { output.WriteMessageArray(7, extension_); } if (options_ != null) { - output.WriteMessage(8, Options); + output.WriteRawTag(66); + output.WriteMessage(Options); } if (sourceCodeInfo_ != null) { - output.WriteMessage(9, SourceCodeInfo); + output.WriteRawTag(74); + output.WriteMessage(SourceCodeInfo); } if (publicDependency_.Count > 0) { output.WriteInt32Array(10, publicDependency_); @@ -541,22 +546,23 @@ namespace Google.Protobuf.DescriptorProtos { output.WriteInt32Array(11, weakDependency_); } if (Syntax.Length != 0) { - output.WriteString(12, Syntax); + output.WriteRawTag(98); + output.WriteString(Syntax); } } public int CalculateSize() { int size = 0; if (Name.Length != 0) { - size += pb::CodedOutputStream.ComputeStringSize(1, Name); + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (Package.Length != 0) { - size += pb::CodedOutputStream.ComputeStringSize(2, Package); + size += 1 + pb::CodedOutputStream.ComputeStringSize(Package); } if (dependency_.Count > 0) { int dataSize = 0; foreach (string element in dependency_) { - dataSize += pb::CodedOutputStream.ComputeStringSizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeStringSize(element); } size += dataSize; size += 1 * dependency_.Count; @@ -564,7 +570,7 @@ namespace Google.Protobuf.DescriptorProtos { if (publicDependency_.Count > 0) { int dataSize = 0; foreach (int element in publicDependency_) { - dataSize += pb::CodedOutputStream.ComputeInt32SizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeInt32Size(element); } size += dataSize; size += 1 * publicDependency_.Count; @@ -572,39 +578,43 @@ namespace Google.Protobuf.DescriptorProtos { if (weakDependency_.Count > 0) { int dataSize = 0; foreach (int element in weakDependency_) { - dataSize += pb::CodedOutputStream.ComputeInt32SizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeInt32Size(element); } size += dataSize; size += 1 * weakDependency_.Count; } if (messageType_.Count > 0) { foreach (global::Google.Protobuf.DescriptorProtos.DescriptorProto element in messageType_) { - size += pb::CodedOutputStream.ComputeMessageSize(4, element); + size += pb::CodedOutputStream.ComputeMessageSize(element); } + size += 1 * messageType_.Count; } if (enumType_.Count > 0) { foreach (global::Google.Protobuf.DescriptorProtos.EnumDescriptorProto element in enumType_) { - size += pb::CodedOutputStream.ComputeMessageSize(5, element); + size += pb::CodedOutputStream.ComputeMessageSize(element); } + size += 1 * enumType_.Count; } if (service_.Count > 0) { foreach (global::Google.Protobuf.DescriptorProtos.ServiceDescriptorProto element in service_) { - size += pb::CodedOutputStream.ComputeMessageSize(6, element); + size += pb::CodedOutputStream.ComputeMessageSize(element); } + size += 1 * service_.Count; } if (extension_.Count > 0) { foreach (global::Google.Protobuf.DescriptorProtos.FieldDescriptorProto element in extension_) { - size += pb::CodedOutputStream.ComputeMessageSize(7, element); + size += pb::CodedOutputStream.ComputeMessageSize(element); } + size += 1 * extension_.Count; } if (options_ != null) { - size += pb::CodedOutputStream.ComputeMessageSize(8, Options); + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options); } if (sourceCodeInfo_ != null) { - size += pb::CodedOutputStream.ComputeMessageSize(9, SourceCodeInfo); + size += 1 + pb::CodedOutputStream.ComputeMessageSize(SourceCodeInfo); } if (Syntax.Length != 0) { - size += pb::CodedOutputStream.ComputeStringSize(12, Syntax); + size += 1 + pb::CodedOutputStream.ComputeStringSize(Syntax); } return size; } @@ -837,7 +847,8 @@ namespace Google.Protobuf.DescriptorProtos { public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { - output.WriteString(1, Name); + output.WriteRawTag(10); + output.WriteString(Name); } if (field_.Count > 0) { output.WriteMessageArray(2, field_); @@ -855,7 +866,8 @@ namespace Google.Protobuf.DescriptorProtos { output.WriteMessageArray(6, extension_); } if (options_ != null) { - output.WriteMessage(7, Options); + output.WriteRawTag(58); + output.WriteMessage(Options); } if (oneofDecl_.Count > 0) { output.WriteMessageArray(8, oneofDecl_); @@ -871,50 +883,57 @@ namespace Google.Protobuf.DescriptorProtos { public int CalculateSize() { int size = 0; if (Name.Length != 0) { - size += pb::CodedOutputStream.ComputeStringSize(1, Name); + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (field_.Count > 0) { foreach (global::Google.Protobuf.DescriptorProtos.FieldDescriptorProto element in field_) { - size += pb::CodedOutputStream.ComputeMessageSize(2, element); + size += pb::CodedOutputStream.ComputeMessageSize(element); } + size += 1 * field_.Count; } if (extension_.Count > 0) { foreach (global::Google.Protobuf.DescriptorProtos.FieldDescriptorProto element in extension_) { - size += pb::CodedOutputStream.ComputeMessageSize(6, element); + size += pb::CodedOutputStream.ComputeMessageSize(element); } + size += 1 * extension_.Count; } if (nestedType_.Count > 0) { foreach (global::Google.Protobuf.DescriptorProtos.DescriptorProto element in nestedType_) { - size += pb::CodedOutputStream.ComputeMessageSize(3, element); + size += pb::CodedOutputStream.ComputeMessageSize(element); } + size += 1 * nestedType_.Count; } if (enumType_.Count > 0) { foreach (global::Google.Protobuf.DescriptorProtos.EnumDescriptorProto element in enumType_) { - size += pb::CodedOutputStream.ComputeMessageSize(4, element); + size += pb::CodedOutputStream.ComputeMessageSize(element); } + size += 1 * enumType_.Count; } if (extensionRange_.Count > 0) { foreach (global::Google.Protobuf.DescriptorProtos.DescriptorProto.Types.ExtensionRange element in extensionRange_) { - size += pb::CodedOutputStream.ComputeMessageSize(5, element); + size += pb::CodedOutputStream.ComputeMessageSize(element); } + size += 1 * extensionRange_.Count; } if (oneofDecl_.Count > 0) { foreach (global::Google.Protobuf.DescriptorProtos.OneofDescriptorProto element in oneofDecl_) { - size += pb::CodedOutputStream.ComputeMessageSize(8, element); + size += pb::CodedOutputStream.ComputeMessageSize(element); } + size += 1 * oneofDecl_.Count; } if (options_ != null) { - size += pb::CodedOutputStream.ComputeMessageSize(7, Options); + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options); } if (reservedRange_.Count > 0) { foreach (global::Google.Protobuf.DescriptorProtos.DescriptorProto.Types.ReservedRange element in reservedRange_) { - size += pb::CodedOutputStream.ComputeMessageSize(9, element); + size += pb::CodedOutputStream.ComputeMessageSize(element); } + size += 1 * reservedRange_.Count; } if (reservedName_.Count > 0) { int dataSize = 0; foreach (string element in reservedName_) { - dataSize += pb::CodedOutputStream.ComputeStringSizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeStringSize(element); } size += dataSize; size += 1 * reservedName_.Count; @@ -1065,20 +1084,22 @@ namespace Google.Protobuf.DescriptorProtos { public void WriteTo(pb::CodedOutputStream output) { if (Start != 0) { - output.WriteInt32(1, Start); + output.WriteRawTag(8); + output.WriteInt32(Start); } if (End != 0) { - output.WriteInt32(2, End); + output.WriteRawTag(16); + output.WriteInt32(End); } } public int CalculateSize() { int size = 0; if (Start != 0) { - size += pb::CodedOutputStream.ComputeInt32Size(1, Start); + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Start); } if (End != 0) { - size += pb::CodedOutputStream.ComputeInt32Size(2, End); + size += 1 + pb::CodedOutputStream.ComputeInt32Size(End); } return size; } @@ -1179,20 +1200,22 @@ namespace Google.Protobuf.DescriptorProtos { public void WriteTo(pb::CodedOutputStream output) { if (Start != 0) { - output.WriteInt32(1, Start); + output.WriteRawTag(8); + output.WriteInt32(Start); } if (End != 0) { - output.WriteInt32(2, End); + output.WriteRawTag(16); + output.WriteInt32(End); } } public int CalculateSize() { int size = 0; if (Start != 0) { - size += pb::CodedOutputStream.ComputeInt32Size(1, Start); + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Start); } if (End != 0) { - size += pb::CodedOutputStream.ComputeInt32Size(2, End); + size += 1 + pb::CodedOutputStream.ComputeInt32Size(End); } return size; } @@ -1366,62 +1389,71 @@ namespace Google.Protobuf.DescriptorProtos { public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { - output.WriteString(1, Name); + output.WriteRawTag(10); + output.WriteString(Name); } if (Extendee.Length != 0) { - output.WriteString(2, Extendee); + output.WriteRawTag(18); + output.WriteString(Extendee); } if (Number != 0) { - output.WriteInt32(3, Number); + output.WriteRawTag(24); + output.WriteInt32(Number); } if (Label != global::Google.Protobuf.DescriptorProtos.FieldDescriptorProto.Types.Label.LABEL_OPTIONAL) { - output.WriteEnum(4, (int) Label); + output.WriteRawTag(32); + output.WriteEnum((int) Label); } if (Type != global::Google.Protobuf.DescriptorProtos.FieldDescriptorProto.Types.Type.TYPE_DOUBLE) { - output.WriteEnum(5, (int) Type); + output.WriteRawTag(40); + output.WriteEnum((int) Type); } if (TypeName.Length != 0) { - output.WriteString(6, TypeName); + output.WriteRawTag(50); + output.WriteString(TypeName); } if (DefaultValue.Length != 0) { - output.WriteString(7, DefaultValue); + output.WriteRawTag(58); + output.WriteString(DefaultValue); } if (options_ != null) { - output.WriteMessage(8, Options); + output.WriteRawTag(66); + output.WriteMessage(Options); } if (OneofIndex != 0) { - output.WriteInt32(9, OneofIndex); + output.WriteRawTag(72); + output.WriteInt32(OneofIndex); } } public int CalculateSize() { int size = 0; if (Name.Length != 0) { - size += pb::CodedOutputStream.ComputeStringSize(1, Name); + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (Number != 0) { - size += pb::CodedOutputStream.ComputeInt32Size(3, Number); + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Number); } if (Label != global::Google.Protobuf.DescriptorProtos.FieldDescriptorProto.Types.Label.LABEL_OPTIONAL) { - size += pb::CodedOutputStream.ComputeEnumSize(4, (int) Label); + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Label); } if (Type != global::Google.Protobuf.DescriptorProtos.FieldDescriptorProto.Types.Type.TYPE_DOUBLE) { - size += pb::CodedOutputStream.ComputeEnumSize(5, (int) Type); + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type); } if (TypeName.Length != 0) { - size += pb::CodedOutputStream.ComputeStringSize(6, TypeName); + size += 1 + pb::CodedOutputStream.ComputeStringSize(TypeName); } if (Extendee.Length != 0) { - size += pb::CodedOutputStream.ComputeStringSize(2, Extendee); + size += 1 + pb::CodedOutputStream.ComputeStringSize(Extendee); } if (DefaultValue.Length != 0) { - size += pb::CodedOutputStream.ComputeStringSize(7, DefaultValue); + size += 1 + pb::CodedOutputStream.ComputeStringSize(DefaultValue); } if (OneofIndex != 0) { - size += pb::CodedOutputStream.ComputeInt32Size(9, OneofIndex); + size += 1 + pb::CodedOutputStream.ComputeInt32Size(OneofIndex); } if (options_ != null) { - size += pb::CodedOutputStream.ComputeMessageSize(8, Options); + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options); } return size; } @@ -1600,14 +1632,15 @@ namespace Google.Protobuf.DescriptorProtos { public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { - output.WriteString(1, Name); + output.WriteRawTag(10); + output.WriteString(Name); } } public int CalculateSize() { int size = 0; if (Name.Length != 0) { - size += pb::CodedOutputStream.ComputeStringSize(1, Name); + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } return size; } @@ -1707,28 +1740,31 @@ namespace Google.Protobuf.DescriptorProtos { public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { - output.WriteString(1, Name); + output.WriteRawTag(10); + output.WriteString(Name); } if (value_.Count > 0) { output.WriteMessageArray(2, value_); } if (options_ != null) { - output.WriteMessage(3, Options); + output.WriteRawTag(26); + output.WriteMessage(Options); } } public int CalculateSize() { int size = 0; if (Name.Length != 0) { - size += pb::CodedOutputStream.ComputeStringSize(1, Name); + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (value_.Count > 0) { foreach (global::Google.Protobuf.DescriptorProtos.EnumValueDescriptorProto element in value_) { - size += pb::CodedOutputStream.ComputeMessageSize(2, element); + size += pb::CodedOutputStream.ComputeMessageSize(element); } + size += 1 * value_.Count; } if (options_ != null) { - size += pb::CodedOutputStream.ComputeMessageSize(3, Options); + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options); } return size; } @@ -1848,26 +1884,29 @@ namespace Google.Protobuf.DescriptorProtos { public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { - output.WriteString(1, Name); + output.WriteRawTag(10); + output.WriteString(Name); } if (Number != 0) { - output.WriteInt32(2, Number); + output.WriteRawTag(16); + output.WriteInt32(Number); } if (options_ != null) { - output.WriteMessage(3, Options); + output.WriteRawTag(26); + output.WriteMessage(Options); } } public int CalculateSize() { int size = 0; if (Name.Length != 0) { - size += pb::CodedOutputStream.ComputeStringSize(1, Name); + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (Number != 0) { - size += pb::CodedOutputStream.ComputeInt32Size(2, Number); + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Number); } if (options_ != null) { - size += pb::CodedOutputStream.ComputeMessageSize(3, Options); + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options); } return size; } @@ -1987,28 +2026,31 @@ namespace Google.Protobuf.DescriptorProtos { public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { - output.WriteString(1, Name); + output.WriteRawTag(10); + output.WriteString(Name); } if (method_.Count > 0) { output.WriteMessageArray(2, method_); } if (options_ != null) { - output.WriteMessage(3, Options); + output.WriteRawTag(26); + output.WriteMessage(Options); } } public int CalculateSize() { int size = 0; if (Name.Length != 0) { - size += pb::CodedOutputStream.ComputeStringSize(1, Name); + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (method_.Count > 0) { foreach (global::Google.Protobuf.DescriptorProtos.MethodDescriptorProto element in method_) { - size += pb::CodedOutputStream.ComputeMessageSize(2, element); + size += pb::CodedOutputStream.ComputeMessageSize(element); } + size += 1 * method_.Count; } if (options_ != null) { - size += pb::CodedOutputStream.ComputeMessageSize(3, Options); + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options); } return size; } @@ -2158,44 +2200,50 @@ namespace Google.Protobuf.DescriptorProtos { public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { - output.WriteString(1, Name); + output.WriteRawTag(10); + output.WriteString(Name); } if (InputType.Length != 0) { - output.WriteString(2, InputType); + output.WriteRawTag(18); + output.WriteString(InputType); } if (OutputType.Length != 0) { - output.WriteString(3, OutputType); + output.WriteRawTag(26); + output.WriteString(OutputType); } if (options_ != null) { - output.WriteMessage(4, Options); + output.WriteRawTag(34); + output.WriteMessage(Options); } if (ClientStreaming != false) { - output.WriteBool(5, ClientStreaming); + output.WriteRawTag(40); + output.WriteBool(ClientStreaming); } if (ServerStreaming != false) { - output.WriteBool(6, ServerStreaming); + output.WriteRawTag(48); + output.WriteBool(ServerStreaming); } } public int CalculateSize() { int size = 0; if (Name.Length != 0) { - size += pb::CodedOutputStream.ComputeStringSize(1, Name); + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (InputType.Length != 0) { - size += pb::CodedOutputStream.ComputeStringSize(2, InputType); + size += 1 + pb::CodedOutputStream.ComputeStringSize(InputType); } if (OutputType.Length != 0) { - size += pb::CodedOutputStream.ComputeStringSize(3, OutputType); + size += 1 + pb::CodedOutputStream.ComputeStringSize(OutputType); } if (options_ != null) { - size += pb::CodedOutputStream.ComputeMessageSize(4, Options); + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options); } if (ClientStreaming != false) { - size += pb::CodedOutputStream.ComputeBoolSize(5, ClientStreaming); + size += 1 + 1; } if (ServerStreaming != false) { - size += pb::CodedOutputStream.ComputeBoolSize(6, ServerStreaming); + size += 1 + 1; } return size; } @@ -2458,46 +2506,60 @@ namespace Google.Protobuf.DescriptorProtos { public void WriteTo(pb::CodedOutputStream output) { if (JavaPackage.Length != 0) { - output.WriteString(1, JavaPackage); + output.WriteRawTag(10); + output.WriteString(JavaPackage); } if (JavaOuterClassname.Length != 0) { - output.WriteString(8, JavaOuterClassname); + output.WriteRawTag(66); + output.WriteString(JavaOuterClassname); } if (OptimizeFor != global::Google.Protobuf.DescriptorProtos.FileOptions.Types.OptimizeMode.SPEED) { - output.WriteEnum(9, (int) OptimizeFor); + output.WriteRawTag(72); + output.WriteEnum((int) OptimizeFor); } if (JavaMultipleFiles != false) { - output.WriteBool(10, JavaMultipleFiles); + output.WriteRawTag(80); + output.WriteBool(JavaMultipleFiles); } if (GoPackage.Length != 0) { - output.WriteString(11, GoPackage); + output.WriteRawTag(90); + output.WriteString(GoPackage); } if (CcGenericServices != false) { - output.WriteBool(16, CcGenericServices); + output.WriteRawTag(128, 1); + output.WriteBool(CcGenericServices); } if (JavaGenericServices != false) { - output.WriteBool(17, JavaGenericServices); + output.WriteRawTag(136, 1); + output.WriteBool(JavaGenericServices); } if (PyGenericServices != false) { - output.WriteBool(18, PyGenericServices); + output.WriteRawTag(144, 1); + output.WriteBool(PyGenericServices); } if (JavaGenerateEqualsAndHash != false) { - output.WriteBool(20, JavaGenerateEqualsAndHash); + output.WriteRawTag(160, 1); + output.WriteBool(JavaGenerateEqualsAndHash); } if (Deprecated != false) { - output.WriteBool(23, Deprecated); + output.WriteRawTag(184, 1); + output.WriteBool(Deprecated); } if (JavaStringCheckUtf8 != false) { - output.WriteBool(27, JavaStringCheckUtf8); + output.WriteRawTag(216, 1); + output.WriteBool(JavaStringCheckUtf8); } if (CcEnableArenas != false) { - output.WriteBool(31, CcEnableArenas); + output.WriteRawTag(248, 1); + output.WriteBool(CcEnableArenas); } if (ObjcClassPrefix.Length != 0) { - output.WriteString(36, ObjcClassPrefix); + output.WriteRawTag(162, 2); + output.WriteString(ObjcClassPrefix); } if (CsharpNamespace.Length != 0) { - output.WriteString(37, CsharpNamespace); + output.WriteRawTag(170, 2); + output.WriteString(CsharpNamespace); } if (uninterpretedOption_.Count > 0) { output.WriteMessageArray(999, uninterpretedOption_); @@ -2507,51 +2569,52 @@ namespace Google.Protobuf.DescriptorProtos { public int CalculateSize() { int size = 0; if (JavaPackage.Length != 0) { - size += pb::CodedOutputStream.ComputeStringSize(1, JavaPackage); + size += 1 + pb::CodedOutputStream.ComputeStringSize(JavaPackage); } if (JavaOuterClassname.Length != 0) { - size += pb::CodedOutputStream.ComputeStringSize(8, JavaOuterClassname); + size += 1 + pb::CodedOutputStream.ComputeStringSize(JavaOuterClassname); } if (JavaMultipleFiles != false) { - size += pb::CodedOutputStream.ComputeBoolSize(10, JavaMultipleFiles); + size += 1 + 1; } if (JavaGenerateEqualsAndHash != false) { - size += pb::CodedOutputStream.ComputeBoolSize(20, JavaGenerateEqualsAndHash); + size += 2 + 1; } if (JavaStringCheckUtf8 != false) { - size += pb::CodedOutputStream.ComputeBoolSize(27, JavaStringCheckUtf8); + size += 2 + 1; } if (OptimizeFor != global::Google.Protobuf.DescriptorProtos.FileOptions.Types.OptimizeMode.SPEED) { - size += pb::CodedOutputStream.ComputeEnumSize(9, (int) OptimizeFor); + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) OptimizeFor); } if (GoPackage.Length != 0) { - size += pb::CodedOutputStream.ComputeStringSize(11, GoPackage); + size += 1 + pb::CodedOutputStream.ComputeStringSize(GoPackage); } if (CcGenericServices != false) { - size += pb::CodedOutputStream.ComputeBoolSize(16, CcGenericServices); + size += 2 + 1; } if (JavaGenericServices != false) { - size += pb::CodedOutputStream.ComputeBoolSize(17, JavaGenericServices); + size += 2 + 1; } if (PyGenericServices != false) { - size += pb::CodedOutputStream.ComputeBoolSize(18, PyGenericServices); + size += 2 + 1; } if (Deprecated != false) { - size += pb::CodedOutputStream.ComputeBoolSize(23, Deprecated); + size += 2 + 1; } if (CcEnableArenas != false) { - size += pb::CodedOutputStream.ComputeBoolSize(31, CcEnableArenas); + size += 2 + 1; } if (ObjcClassPrefix.Length != 0) { - size += pb::CodedOutputStream.ComputeStringSize(36, ObjcClassPrefix); + size += 2 + pb::CodedOutputStream.ComputeStringSize(ObjcClassPrefix); } if (CsharpNamespace.Length != 0) { - size += pb::CodedOutputStream.ComputeStringSize(37, CsharpNamespace); + size += 2 + pb::CodedOutputStream.ComputeStringSize(CsharpNamespace); } if (uninterpretedOption_.Count > 0) { foreach (global::Google.Protobuf.DescriptorProtos.UninterpretedOption element in uninterpretedOption_) { - size += pb::CodedOutputStream.ComputeMessageSize(999, element); + size += pb::CodedOutputStream.ComputeMessageSize(element); } + size += 2 * uninterpretedOption_.Count; } return size; } @@ -2781,16 +2844,20 @@ namespace Google.Protobuf.DescriptorProtos { public void WriteTo(pb::CodedOutputStream output) { if (MessageSetWireFormat != false) { - output.WriteBool(1, MessageSetWireFormat); + output.WriteRawTag(8); + output.WriteBool(MessageSetWireFormat); } if (NoStandardDescriptorAccessor != false) { - output.WriteBool(2, NoStandardDescriptorAccessor); + output.WriteRawTag(16); + output.WriteBool(NoStandardDescriptorAccessor); } if (Deprecated != false) { - output.WriteBool(3, Deprecated); + output.WriteRawTag(24); + output.WriteBool(Deprecated); } if (MapEntry != false) { - output.WriteBool(7, MapEntry); + output.WriteRawTag(56); + output.WriteBool(MapEntry); } if (uninterpretedOption_.Count > 0) { output.WriteMessageArray(999, uninterpretedOption_); @@ -2800,21 +2867,22 @@ namespace Google.Protobuf.DescriptorProtos { public int CalculateSize() { int size = 0; if (MessageSetWireFormat != false) { - size += pb::CodedOutputStream.ComputeBoolSize(1, MessageSetWireFormat); + size += 1 + 1; } if (NoStandardDescriptorAccessor != false) { - size += pb::CodedOutputStream.ComputeBoolSize(2, NoStandardDescriptorAccessor); + size += 1 + 1; } if (Deprecated != false) { - size += pb::CodedOutputStream.ComputeBoolSize(3, Deprecated); + size += 1 + 1; } if (MapEntry != false) { - size += pb::CodedOutputStream.ComputeBoolSize(7, MapEntry); + size += 1 + 1; } if (uninterpretedOption_.Count > 0) { foreach (global::Google.Protobuf.DescriptorProtos.UninterpretedOption element in uninterpretedOption_) { - size += pb::CodedOutputStream.ComputeMessageSize(999, element); + size += pb::CodedOutputStream.ComputeMessageSize(element); } + size += 2 * uninterpretedOption_.Count; } return size; } @@ -2982,22 +3050,28 @@ namespace Google.Protobuf.DescriptorProtos { public void WriteTo(pb::CodedOutputStream output) { if (Ctype != global::Google.Protobuf.DescriptorProtos.FieldOptions.Types.CType.STRING) { - output.WriteEnum(1, (int) Ctype); + output.WriteRawTag(8); + output.WriteEnum((int) Ctype); } if (Packed != false) { - output.WriteBool(2, Packed); + output.WriteRawTag(16); + output.WriteBool(Packed); } if (Deprecated != false) { - output.WriteBool(3, Deprecated); + output.WriteRawTag(24); + output.WriteBool(Deprecated); } if (Lazy != false) { - output.WriteBool(5, Lazy); + output.WriteRawTag(40); + output.WriteBool(Lazy); } if (Jstype != global::Google.Protobuf.DescriptorProtos.FieldOptions.Types.JSType.JS_NORMAL) { - output.WriteEnum(6, (int) Jstype); + output.WriteRawTag(48); + output.WriteEnum((int) Jstype); } if (Weak != false) { - output.WriteBool(10, Weak); + output.WriteRawTag(80); + output.WriteBool(Weak); } if (uninterpretedOption_.Count > 0) { output.WriteMessageArray(999, uninterpretedOption_); @@ -3007,27 +3081,28 @@ namespace Google.Protobuf.DescriptorProtos { public int CalculateSize() { int size = 0; if (Ctype != global::Google.Protobuf.DescriptorProtos.FieldOptions.Types.CType.STRING) { - size += pb::CodedOutputStream.ComputeEnumSize(1, (int) Ctype); + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Ctype); } if (Packed != false) { - size += pb::CodedOutputStream.ComputeBoolSize(2, Packed); + size += 1 + 1; } if (Jstype != global::Google.Protobuf.DescriptorProtos.FieldOptions.Types.JSType.JS_NORMAL) { - size += pb::CodedOutputStream.ComputeEnumSize(6, (int) Jstype); + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Jstype); } if (Lazy != false) { - size += pb::CodedOutputStream.ComputeBoolSize(5, Lazy); + size += 1 + 1; } if (Deprecated != false) { - size += pb::CodedOutputStream.ComputeBoolSize(3, Deprecated); + size += 1 + 1; } if (Weak != false) { - size += pb::CodedOutputStream.ComputeBoolSize(10, Weak); + size += 1 + 1; } if (uninterpretedOption_.Count > 0) { foreach (global::Google.Protobuf.DescriptorProtos.UninterpretedOption element in uninterpretedOption_) { - size += pb::CodedOutputStream.ComputeMessageSize(999, element); + size += pb::CodedOutputStream.ComputeMessageSize(element); } + size += 2 * uninterpretedOption_.Count; } return size; } @@ -3187,10 +3262,12 @@ namespace Google.Protobuf.DescriptorProtos { public void WriteTo(pb::CodedOutputStream output) { if (AllowAlias != false) { - output.WriteBool(2, AllowAlias); + output.WriteRawTag(16); + output.WriteBool(AllowAlias); } if (Deprecated != false) { - output.WriteBool(3, Deprecated); + output.WriteRawTag(24); + output.WriteBool(Deprecated); } if (uninterpretedOption_.Count > 0) { output.WriteMessageArray(999, uninterpretedOption_); @@ -3200,15 +3277,16 @@ namespace Google.Protobuf.DescriptorProtos { public int CalculateSize() { int size = 0; if (AllowAlias != false) { - size += pb::CodedOutputStream.ComputeBoolSize(2, AllowAlias); + size += 1 + 1; } if (Deprecated != false) { - size += pb::CodedOutputStream.ComputeBoolSize(3, Deprecated); + size += 1 + 1; } if (uninterpretedOption_.Count > 0) { foreach (global::Google.Protobuf.DescriptorProtos.UninterpretedOption element in uninterpretedOption_) { - size += pb::CodedOutputStream.ComputeMessageSize(999, element); + size += pb::CodedOutputStream.ComputeMessageSize(element); } + size += 2 * uninterpretedOption_.Count; } return size; } @@ -3312,7 +3390,8 @@ namespace Google.Protobuf.DescriptorProtos { public void WriteTo(pb::CodedOutputStream output) { if (Deprecated != false) { - output.WriteBool(1, Deprecated); + output.WriteRawTag(8); + output.WriteBool(Deprecated); } if (uninterpretedOption_.Count > 0) { output.WriteMessageArray(999, uninterpretedOption_); @@ -3322,12 +3401,13 @@ namespace Google.Protobuf.DescriptorProtos { public int CalculateSize() { int size = 0; if (Deprecated != false) { - size += pb::CodedOutputStream.ComputeBoolSize(1, Deprecated); + size += 1 + 1; } if (uninterpretedOption_.Count > 0) { foreach (global::Google.Protobuf.DescriptorProtos.UninterpretedOption element in uninterpretedOption_) { - size += pb::CodedOutputStream.ComputeMessageSize(999, element); + size += pb::CodedOutputStream.ComputeMessageSize(element); } + size += 2 * uninterpretedOption_.Count; } return size; } @@ -3424,7 +3504,8 @@ namespace Google.Protobuf.DescriptorProtos { public void WriteTo(pb::CodedOutputStream output) { if (Deprecated != false) { - output.WriteBool(33, Deprecated); + output.WriteRawTag(136, 2); + output.WriteBool(Deprecated); } if (uninterpretedOption_.Count > 0) { output.WriteMessageArray(999, uninterpretedOption_); @@ -3434,12 +3515,13 @@ namespace Google.Protobuf.DescriptorProtos { public int CalculateSize() { int size = 0; if (Deprecated != false) { - size += pb::CodedOutputStream.ComputeBoolSize(33, Deprecated); + size += 2 + 1; } if (uninterpretedOption_.Count > 0) { foreach (global::Google.Protobuf.DescriptorProtos.UninterpretedOption element in uninterpretedOption_) { - size += pb::CodedOutputStream.ComputeMessageSize(999, element); + size += pb::CodedOutputStream.ComputeMessageSize(element); } + size += 2 * uninterpretedOption_.Count; } return size; } @@ -3536,7 +3618,8 @@ namespace Google.Protobuf.DescriptorProtos { public void WriteTo(pb::CodedOutputStream output) { if (Deprecated != false) { - output.WriteBool(33, Deprecated); + output.WriteRawTag(136, 2); + output.WriteBool(Deprecated); } if (uninterpretedOption_.Count > 0) { output.WriteMessageArray(999, uninterpretedOption_); @@ -3546,12 +3629,13 @@ namespace Google.Protobuf.DescriptorProtos { public int CalculateSize() { int size = 0; if (Deprecated != false) { - size += pb::CodedOutputStream.ComputeBoolSize(33, Deprecated); + size += 2 + 1; } if (uninterpretedOption_.Count > 0) { foreach (global::Google.Protobuf.DescriptorProtos.UninterpretedOption element in uninterpretedOption_) { - size += pb::CodedOutputStream.ComputeMessageSize(999, element); + size += pb::CodedOutputStream.ComputeMessageSize(element); } + size += 2 * uninterpretedOption_.Count; } return size; } @@ -3701,22 +3785,28 @@ namespace Google.Protobuf.DescriptorProtos { output.WriteMessageArray(2, name_); } if (IdentifierValue.Length != 0) { - output.WriteString(3, IdentifierValue); + output.WriteRawTag(26); + output.WriteString(IdentifierValue); } if (PositiveIntValue != 0UL) { - output.WriteUInt64(4, PositiveIntValue); + output.WriteRawTag(32); + output.WriteUInt64(PositiveIntValue); } if (NegativeIntValue != 0L) { - output.WriteInt64(5, NegativeIntValue); + output.WriteRawTag(40); + output.WriteInt64(NegativeIntValue); } if (DoubleValue != 0D) { - output.WriteDouble(6, DoubleValue); + output.WriteRawTag(49); + output.WriteDouble(DoubleValue); } if (StringValue.Length != 0) { - output.WriteBytes(7, StringValue); + output.WriteRawTag(58); + output.WriteBytes(StringValue); } if (AggregateValue.Length != 0) { - output.WriteString(8, AggregateValue); + output.WriteRawTag(66); + output.WriteString(AggregateValue); } } @@ -3724,26 +3814,27 @@ namespace Google.Protobuf.DescriptorProtos { int size = 0; if (name_.Count > 0) { foreach (global::Google.Protobuf.DescriptorProtos.UninterpretedOption.Types.NamePart element in name_) { - size += pb::CodedOutputStream.ComputeMessageSize(2, element); + size += pb::CodedOutputStream.ComputeMessageSize(element); } + size += 1 * name_.Count; } if (IdentifierValue.Length != 0) { - size += pb::CodedOutputStream.ComputeStringSize(3, IdentifierValue); + size += 1 + pb::CodedOutputStream.ComputeStringSize(IdentifierValue); } if (PositiveIntValue != 0UL) { - size += pb::CodedOutputStream.ComputeUInt64Size(4, PositiveIntValue); + size += 1 + pb::CodedOutputStream.ComputeUInt64Size(PositiveIntValue); } if (NegativeIntValue != 0L) { - size += pb::CodedOutputStream.ComputeInt64Size(5, NegativeIntValue); + size += 1 + pb::CodedOutputStream.ComputeInt64Size(NegativeIntValue); } if (DoubleValue != 0D) { - size += pb::CodedOutputStream.ComputeDoubleSize(6, DoubleValue); + size += 1 + 8; } if (StringValue.Length != 0) { - size += pb::CodedOutputStream.ComputeBytesSize(7, StringValue); + size += 1 + pb::CodedOutputStream.ComputeBytesSize(StringValue); } if (AggregateValue.Length != 0) { - size += pb::CodedOutputStream.ComputeStringSize(8, AggregateValue); + size += 1 + pb::CodedOutputStream.ComputeStringSize(AggregateValue); } return size; } @@ -3878,20 +3969,22 @@ namespace Google.Protobuf.DescriptorProtos { public void WriteTo(pb::CodedOutputStream output) { if (NamePart_.Length != 0) { - output.WriteString(1, NamePart_); + output.WriteRawTag(10); + output.WriteString(NamePart_); } if (IsExtension != false) { - output.WriteBool(2, IsExtension); + output.WriteRawTag(16); + output.WriteBool(IsExtension); } } public int CalculateSize() { int size = 0; if (NamePart_.Length != 0) { - size += pb::CodedOutputStream.ComputeStringSize(1, NamePart_); + size += 1 + pb::CodedOutputStream.ComputeStringSize(NamePart_); } if (IsExtension != false) { - size += pb::CodedOutputStream.ComputeBoolSize(2, IsExtension); + size += 1 + 1; } return size; } @@ -3993,8 +4086,9 @@ namespace Google.Protobuf.DescriptorProtos { int size = 0; if (location_.Count > 0) { foreach (global::Google.Protobuf.DescriptorProtos.SourceCodeInfo.Types.Location element in location_) { - size += pb::CodedOutputStream.ComputeMessageSize(1, element); + size += pb::CodedOutputStream.ComputeMessageSize(element); } + size += 1 * location_.Count; } return size; } @@ -4111,16 +4205,20 @@ namespace Google.Protobuf.DescriptorProtos { public void WriteTo(pb::CodedOutputStream output) { if (path_.Count > 0) { - output.WritePackedInt32Array(1, path_); + output.WriteRawTag(10); + output.WritePackedInt32Array(path_); } if (span_.Count > 0) { - output.WritePackedInt32Array(2, span_); + output.WriteRawTag(18); + output.WritePackedInt32Array(span_); } if (LeadingComments.Length != 0) { - output.WriteString(3, LeadingComments); + output.WriteRawTag(26); + output.WriteString(LeadingComments); } if (TrailingComments.Length != 0) { - output.WriteString(4, TrailingComments); + output.WriteRawTag(34); + output.WriteString(TrailingComments); } if (leadingDetachedComments_.Count > 0) { output.WriteStringArray(6, leadingDetachedComments_); @@ -4132,29 +4230,29 @@ namespace Google.Protobuf.DescriptorProtos { if (path_.Count > 0) { int dataSize = 0; foreach (int element in path_) { - dataSize += pb::CodedOutputStream.ComputeInt32SizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeInt32Size(element); } size += dataSize; - size += 1 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 1 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (span_.Count > 0) { int dataSize = 0; foreach (int element in span_) { - dataSize += pb::CodedOutputStream.ComputeInt32SizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeInt32Size(element); } size += dataSize; - size += 1 + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize); + size += 1 + pb::CodedOutputStream.ComputeInt32Size(dataSize); } if (LeadingComments.Length != 0) { - size += pb::CodedOutputStream.ComputeStringSize(3, LeadingComments); + size += 1 + pb::CodedOutputStream.ComputeStringSize(LeadingComments); } if (TrailingComments.Length != 0) { - size += pb::CodedOutputStream.ComputeStringSize(4, TrailingComments); + size += 1 + pb::CodedOutputStream.ComputeStringSize(TrailingComments); } if (leadingDetachedComments_.Count > 0) { int dataSize = 0; foreach (string element in leadingDetachedComments_) { - dataSize += pb::CodedOutputStream.ComputeStringSizeNoTag(element); + dataSize += pb::CodedOutputStream.ComputeStringSize(element); } size += dataSize; size += 1 * leadingDetachedComments_.Count; diff --git a/src/google/protobuf/compiler/csharp/csharp_enum_field.cc b/src/google/protobuf/compiler/csharp/csharp_enum_field.cc index 19fd50cf..af34f50c 100644 --- a/src/google/protobuf/compiler/csharp/csharp_enum_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_enum_field.cc @@ -61,7 +61,8 @@ void EnumFieldGenerator::GenerateParsingCode(io::Printer* printer) { void EnumFieldGenerator::GenerateSerializationCode(io::Printer* printer) { printer->Print(variables_, "if ($has_property_check$) {\n" - " output.WriteEnum($number$, (int) $property_name$);\n" + " output.WriteRawTag($tag_bytes$);\n" + " output.WriteEnum((int) $property_name$);\n" "}\n"); } @@ -69,7 +70,7 @@ void EnumFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { printer->Print( variables_, "if ($has_property_check$) {\n" - " size += pb::CodedOutputStream.ComputeEnumSize($number$, (int) $property_name$);\n" + " size += $tag_size$ + pb::CodedOutputStream.ComputeEnumSize((int) $property_name$);\n" "}\n"); } @@ -93,7 +94,8 @@ void EnumOneofFieldGenerator::GenerateSerializationCode(io::Printer* printer) { printer->Print( variables_, "if ($has_property_check$) {\n" - " output.WriteEnum($number$, (int) $property_name$);\n" + " output.WriteRawTag($tag_bytes$);\n" + " output.WriteEnum((int) $property_name$);\n" "}\n"); } @@ -101,7 +103,7 @@ void EnumOneofFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { printer->Print( variables_, "if ($has_property_check$) {\n" - " size += pb::CodedOutputStream.ComputeEnumSize($number$, (int) $property_name$);\n" + " size += $tag_size$ + pb::CodedOutputStream.ComputeEnumSize((int) $property_name$);\n" "}\n"); } diff --git a/src/google/protobuf/compiler/csharp/csharp_field_base.cc b/src/google/protobuf/compiler/csharp/csharp_field_base.cc index ec0d51ca..54f281ee 100644 --- a/src/google/protobuf/compiler/csharp/csharp_field_base.cc +++ b/src/google/protobuf/compiler/csharp/csharp_field_base.cc @@ -35,6 +35,7 @@ #include #include #include +#include #include #include #include @@ -55,8 +56,18 @@ void FieldGeneratorBase::SetCommonFieldVariables( // Note: this will be valid even though the tag emitted for packed and unpacked versions of // repeated fields varies by wire format. The wire format is encoded in the bottom 3 bits, which // never effects the tag size. - int tagSize = internal::WireFormat::TagSize(descriptor_->number(), descriptor_->type()); - (*variables)["tag_size"] = SimpleItoa(tagSize); + int tag_size = internal::WireFormat::TagSize(descriptor_->number(), descriptor_->type()); + uint tag = internal::WireFormat::MakeTag(descriptor_); + uint8 tag_array[5]; + io::CodedOutputStream::WriteTagToArray(tag, tag_array); + string tag_bytes = SimpleItoa(tag_array[0]); + for (int i = 1; i < tag_size; i++) { + tag_bytes += ", " + SimpleItoa(tag_array[i]); + } + + (*variables)["tag_size"] = SimpleItoa(tag_size); + (*variables)["tag_bytes"] = tag_bytes; + (*variables)["property_name"] = property_name(); (*variables)["type_name"] = type_name(); (*variables)["name"] = name(); diff --git a/src/google/protobuf/compiler/csharp/csharp_message_field.cc b/src/google/protobuf/compiler/csharp/csharp_message_field.cc index 804a5ae2..bd67aa0f 100644 --- a/src/google/protobuf/compiler/csharp/csharp_message_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_message_field.cc @@ -92,11 +92,11 @@ void MessageFieldGenerator::GenerateParsingCode(io::Printer* printer) { } void MessageFieldGenerator::GenerateSerializationCode(io::Printer* printer) { - // TODO(jonskeet): Why are we using array access instead of a literal here? printer->Print( variables_, "if ($has_property_check$) {\n" - " output.WriteMessage($number$, $property_name$);\n" + " output.WriteRawTag($tag_bytes$);\n" + " output.WriteMessage($property_name$);\n" "}\n"); } @@ -104,7 +104,7 @@ void MessageFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { printer->Print( variables_, "if ($has_property_check$) {\n" - " size += pb::CodedOutputStream.ComputeMessageSize($number$, $property_name$);\n" + " size += $tag_size$ + pb::CodedOutputStream.ComputeMessageSize($property_name$);\n" "}\n"); } diff --git a/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc b/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc index 0164cdca..5820eb37 100644 --- a/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc @@ -105,16 +105,29 @@ void PrimitiveFieldGenerator::GenerateSerializationCode(io::Printer* printer) { printer->Print( variables_, "if ($has_property_check$) {\n" - " output.Write$capitalized_type_name$($number$, $property_name$);\n" + " output.WriteRawTag($tag_bytes$);\n" + " output.Write$capitalized_type_name$($property_name$);\n" "}\n"); } void PrimitiveFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { printer->Print( variables_, - "if ($has_property_check$) {\n" - " size += pb::CodedOutputStream.Compute$capitalized_type_name$Size($number$, $property_name$);\n" - "}\n"); + "if ($has_property_check$) {\n"); + printer->Indent(); + int fixedSize = GetFixedSize(descriptor_->type()); + if (fixedSize == -1) { + printer->Print( + variables_, + "size += $tag_size$ + pb::CodedOutputStream.Compute$capitalized_type_name$Size($property_name$);\n"); + } else { + printer->Print( + "size += $tag_size$ + $fixed_size$;\n", + "fixed_size", SimpleItoa(fixedSize), + "tag_size", variables_["tag_size"]); + } + printer->Outdent(); + printer->Print("}\n"); } void PrimitiveFieldGenerator::WriteHash(io::Printer* printer) { @@ -173,7 +186,7 @@ void PrimitiveOneofFieldGenerator::WriteToString(io::Printer* printer) { void PrimitiveOneofFieldGenerator::GenerateParsingCode(io::Printer* printer) { printer->Print( variables_, - "$property_name$ = input.Read$capitalized_type_name$()\n;"); + "$property_name$ = input.Read$capitalized_type_name$();\n"); } } // namespace csharp diff --git a/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc b/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc index 22dec710..c78aaef6 100644 --- a/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc @@ -82,9 +82,20 @@ void RepeatedEnumFieldGenerator::GenerateParsingCode(io::Printer* printer) { void RepeatedEnumFieldGenerator::GenerateSerializationCode(io::Printer* printer) { printer->Print( variables_, - "if ($name$_.Count > 0) {\n" - " output.Write$packed$EnumArray($number$, $name$_);\n" - "}\n"); + "if ($name$_.Count > 0) {\n"); + printer->Indent(); + if (descriptor_->is_packed()) { + printer->Print( + variables_, + "output.WriteRawTag($tag_bytes$);\n" + "output.WritePackedEnumArray($name$_);\n"); + } else { + printer->Print( + variables_, + "output.Write$capitalized_type_name$Array($number$, $name$_);\n"); + } + printer->Outdent(); + printer->Print("}\n"); } void RepeatedEnumFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { @@ -97,14 +108,13 @@ void RepeatedEnumFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer printer->Print( variables_, "foreach ($type_name$ element in $name$_) {\n" - " dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag((int) element);\n" + " dataSize += pb::CodedOutputStream.ComputeEnumSize((int) element);\n" "}\n" "size += dataSize;\n"); int tagSize = internal::WireFormat::TagSize(descriptor_->number(), descriptor_->type()); if (descriptor_->is_packed()) { printer->Print( - "size += $tag_size$;\n" - "size += pb::CodedOutputStream.ComputeRawVarint32Size((uint) dataSize);\n", + "size += $tag_size$ + pb::CodedOutputStream.ComputeRawVarint32Size((uint) dataSize);\n", "tag_size", SimpleItoa(tagSize)); } else { printer->Print( diff --git a/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc b/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc index 4b570d3b..3553fe12 100644 --- a/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc @@ -79,8 +79,8 @@ void RepeatedMessageFieldGenerator::GenerateParsingCode(io::Printer* printer) { } void RepeatedMessageFieldGenerator::GenerateSerializationCode(io::Printer* printer) { - // TODO(jonskeet): Originally, this checked for Count > 0 first. - // The Write* call should make that cheap though - no need to generate it every time. + // TODO(jonskeet): Bake the foreach loop into the generated code? We lose the + // advantage of knowing the tag bytes this way :( printer->Print( variables_, "if ($name$_.Count > 0) {\n" @@ -89,13 +89,13 @@ void RepeatedMessageFieldGenerator::GenerateSerializationCode(io::Printer* print } void RepeatedMessageFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { - // TODO(jonskeet): Put this into CodedOutputStream. printer->Print( variables_, "if ($name$_.Count > 0) {\n" " foreach ($type_name$ element in $name$_) {\n" - " size += pb::CodedOutputStream.ComputeMessageSize($number$, element);\n" + " size += pb::CodedOutputStream.ComputeMessageSize(element);\n" " }\n" + " size += $tag_size$ * $name$_.Count;\n" "}\n"); } diff --git a/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc b/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc index a5457785..fe8a4364 100644 --- a/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc @@ -82,9 +82,20 @@ void RepeatedPrimitiveFieldGenerator::GenerateSerializationCode( io::Printer* printer) { printer->Print( variables_, - "if ($name$_.Count > 0) {\n" - " output.Write$packed$$capitalized_type_name$Array($number$, $name$_);\n" - "}\n"); + "if ($name$_.Count > 0) {\n"); + printer->Indent(); + if (descriptor_->is_packed()) { + printer->Print( + variables_, + "output.WriteRawTag($tag_bytes$);\n" + "output.WritePacked$capitalized_type_name$Array($name$_);\n"); + } else { + printer->Print( + variables_, + "output.Write$capitalized_type_name$Array($number$, $name$_);\n"); + } + printer->Outdent(); + printer->Print("}\n"); } void RepeatedPrimitiveFieldGenerator::GenerateSerializedSizeCode( @@ -100,7 +111,7 @@ void RepeatedPrimitiveFieldGenerator::GenerateSerializedSizeCode( printer->Print( variables_, "foreach ($type_name$ element in $name$_) {\n" - " dataSize += pb::CodedOutputStream.Compute$capitalized_type_name$SizeNoTag(element);\n" + " dataSize += pb::CodedOutputStream.Compute$capitalized_type_name$Size(element);\n" "}\n"); } else { printer->Print( @@ -111,7 +122,7 @@ void RepeatedPrimitiveFieldGenerator::GenerateSerializedSizeCode( int tagSize = internal::WireFormat::TagSize(descriptor_->number(), descriptor_->type()); if (descriptor_->is_packed()) { printer->Print( - "size += $tag_size$ + pb::CodedOutputStream.ComputeInt32SizeNoTag(dataSize);\n", + "size += $tag_size$ + pb::CodedOutputStream.ComputeInt32Size(dataSize);\n", "tag_size", SimpleItoa(tagSize)); } else { printer->Print( diff --git a/src/google/protobuf/wire_format.h b/src/google/protobuf/wire_format.h index 8de491a6..84270fee 100644 --- a/src/google/protobuf/wire_format.h +++ b/src/google/protobuf/wire_format.h @@ -290,7 +290,7 @@ class LIBPROTOBUF_EXPORT UnknownFieldSetFieldSkipper : public FieldSkipper { inline WireFormatLite::WireType WireFormat::WireTypeForField( const FieldDescriptor* field) { - if (field->options().packed()) { + if (field->is_packed()) { return WireFormatLite::WIRETYPE_LENGTH_DELIMITED; } else { return WireTypeForFieldType(field->type()); -- cgit v1.2.3 From cdeda4b87625084f5687115bb1fd7772b7c34ad6 Mon Sep 17 00:00:00 2001 From: Jon Skeet Date: Fri, 19 Jun 2015 17:30:13 +0100 Subject: Minor cleanup. - Make some members internal - Remove a lot of FrameworkPortability that isn't required - Start adding documentation comments - Remove some more group-based members - Not passing in "the last tag read" into Read*Array, g --- csharp/src/AddressBook/Addressbook.cs | 4 +- .../ProtocolBuffers.Test/CodedInputStreamTest.cs | 4 +- .../ProtocolBuffers.Test/CodedOutputStreamTest.cs | 4 +- .../TestProtos/UnittestIssues.cs | 10 +- .../TestProtos/UnittestProto3.cs | 124 ++++++++++----------- csharp/src/ProtocolBuffers/ByteArray.cs | 9 +- csharp/src/ProtocolBuffers/CodedInputStream.cs | 90 +++++++-------- csharp/src/ProtocolBuffers/CodedOutputStream.cs | 5 +- .../DescriptorProtos/DescriptorProtoFile.cs | 60 +++++----- csharp/src/ProtocolBuffers/Extensions.cs | 70 ------------ csharp/src/ProtocolBuffers/FrameworkPortability.cs | 68 +---------- csharp/src/ProtocolBuffers/IMessage.cs | 43 ++++++- csharp/src/ProtocolBuffers/MessageExtensions.cs | 81 ++++++++++++++ csharp/src/ProtocolBuffers/MessageParser.cs | 37 +++++- csharp/src/ProtocolBuffers/ProtocolBuffers.csproj | 4 +- csharp/src/ProtocolBuffers/ThrowHelper.cs | 17 +-- .../compiler/csharp/csharp_repeated_enum_field.cc | 2 +- .../csharp/csharp_repeated_message_field.cc | 2 +- .../csharp/csharp_repeated_primitive_field.cc | 2 +- 19 files changed, 319 insertions(+), 317 deletions(-) delete mode 100644 csharp/src/ProtocolBuffers/Extensions.cs create mode 100644 csharp/src/ProtocolBuffers/MessageExtensions.cs (limited to 'src/google') diff --git a/csharp/src/AddressBook/Addressbook.cs b/csharp/src/AddressBook/Addressbook.cs index 480fb92a..322f85f7 100644 --- a/csharp/src/AddressBook/Addressbook.cs +++ b/csharp/src/AddressBook/Addressbook.cs @@ -214,7 +214,7 @@ namespace Google.ProtocolBuffers.Examples.AddressBook { break; } case 34: { - input.ReadMessageArray(tag, phone_, global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.Parser); + input.ReadMessageArray(phone_, global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.Parser); break; } } @@ -432,7 +432,7 @@ namespace Google.ProtocolBuffers.Examples.AddressBook { } break; case 10: { - input.ReadMessageArray(tag, person_, global::Google.ProtocolBuffers.Examples.AddressBook.Person.Parser); + input.ReadMessageArray(person_, global::Google.ProtocolBuffers.Examples.AddressBook.Person.Parser); break; } } diff --git a/csharp/src/ProtocolBuffers.Test/CodedInputStreamTest.cs b/csharp/src/ProtocolBuffers.Test/CodedInputStreamTest.cs index 0baa3a75..52757d4d 100644 --- a/csharp/src/ProtocolBuffers.Test/CodedInputStreamTest.cs +++ b/csharp/src/ProtocolBuffers.Test/CodedInputStreamTest.cs @@ -489,7 +489,7 @@ namespace Google.Protobuf Assert.IsTrue(input.ReadTag(out tag)); RepeatedField values = new RepeatedField(); - input.ReadEnumArray(tag, values); + input.ReadEnumArray(values); Assert.AreEqual(6, values.Count); Assert.AreEqual(TestNegEnum.None, values[0]); @@ -513,7 +513,7 @@ namespace Google.Protobuf Assert.IsTrue(input.ReadTag(out tag)); RepeatedField values = new RepeatedField(); - input.ReadEnumArray(tag, values); + input.ReadEnumArray(values); Assert.AreEqual(6, values.Count); Assert.AreEqual(TestNegEnum.None, values[0]); diff --git a/csharp/src/ProtocolBuffers.Test/CodedOutputStreamTest.cs b/csharp/src/ProtocolBuffers.Test/CodedOutputStreamTest.cs index bc053e19..223374e0 100644 --- a/csharp/src/ProtocolBuffers.Test/CodedOutputStreamTest.cs +++ b/csharp/src/ProtocolBuffers.Test/CodedOutputStreamTest.cs @@ -326,7 +326,7 @@ namespace Google.Protobuf Assert.IsTrue(input.ReadTag(out tag)); List values = new List(); - input.ReadInt32Array(tag, values); + input.ReadInt32Array(values); Assert.AreEqual(6, values.Count); for (int i = 0; i > -6; i--) @@ -349,7 +349,7 @@ namespace Google.Protobuf Assert.IsTrue(input.ReadTag(out tag)); List values = new List(); - input.ReadInt32Array(tag, values); + input.ReadInt32Array(values); Assert.AreEqual(6, values.Count); for (int i = 0; i > -6; i--) diff --git a/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestIssues.cs b/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestIssues.cs index 1ea3728d..959b3866 100644 --- a/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestIssues.cs +++ b/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestIssues.cs @@ -218,12 +218,12 @@ namespace UnitTest.Issues.TestProtos { } case 18: case 16: { - input.ReadEnumArray(tag, values_); + input.ReadEnumArray(values_); break; } case 26: case 24: { - input.ReadEnumArray(tag, packedValues_); + input.ReadEnumArray(packedValues_); break; } } @@ -495,7 +495,7 @@ namespace UnitTest.Issues.TestProtos { } case 18: case 16: { - input.ReadInt32Array(tag, primitiveArray_); + input.ReadInt32Array(primitiveArray_); break; } case 26: { @@ -506,7 +506,7 @@ namespace UnitTest.Issues.TestProtos { break; } case 34: { - input.ReadMessageArray(tag, messageArray_, global::UnitTest.Issues.TestProtos.DeprecatedChild.Parser); + input.ReadMessageArray(messageArray_, global::UnitTest.Issues.TestProtos.DeprecatedChild.Parser); break; } case 40: { @@ -515,7 +515,7 @@ namespace UnitTest.Issues.TestProtos { } case 50: case 48: { - input.ReadEnumArray(tag, enumArray_); + input.ReadEnumArray(enumArray_); break; } } diff --git a/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestProto3.cs b/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestProto3.cs index a2c5d5f6..bbfa8c3e 100644 --- a/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestProto3.cs +++ b/csharp/src/ProtocolBuffers.Test/TestProtos/UnittestProto3.cs @@ -1547,106 +1547,106 @@ namespace Google.Protobuf.TestProtos { } case 250: case 248: { - input.ReadInt32Array(tag, repeatedInt32_); + input.ReadInt32Array(repeatedInt32_); break; } case 258: case 256: { - input.ReadInt64Array(tag, repeatedInt64_); + input.ReadInt64Array(repeatedInt64_); break; } case 266: case 264: { - input.ReadUInt32Array(tag, repeatedUint32_); + input.ReadUInt32Array(repeatedUint32_); break; } case 274: case 272: { - input.ReadUInt64Array(tag, repeatedUint64_); + input.ReadUInt64Array(repeatedUint64_); break; } case 282: case 280: { - input.ReadSInt32Array(tag, repeatedSint32_); + input.ReadSInt32Array(repeatedSint32_); break; } case 290: case 288: { - input.ReadSInt64Array(tag, repeatedSint64_); + input.ReadSInt64Array(repeatedSint64_); break; } case 298: case 301: { - input.ReadFixed32Array(tag, repeatedFixed32_); + input.ReadFixed32Array(repeatedFixed32_); break; } case 306: case 305: { - input.ReadFixed64Array(tag, repeatedFixed64_); + input.ReadFixed64Array(repeatedFixed64_); break; } case 314: case 317: { - input.ReadSFixed32Array(tag, repeatedSfixed32_); + input.ReadSFixed32Array(repeatedSfixed32_); break; } case 322: case 321: { - input.ReadSFixed64Array(tag, repeatedSfixed64_); + input.ReadSFixed64Array(repeatedSfixed64_); break; } case 330: case 333: { - input.ReadFloatArray(tag, repeatedFloat_); + input.ReadFloatArray(repeatedFloat_); break; } case 338: case 337: { - input.ReadDoubleArray(tag, repeatedDouble_); + input.ReadDoubleArray(repeatedDouble_); break; } case 346: case 344: { - input.ReadBoolArray(tag, repeatedBool_); + input.ReadBoolArray(repeatedBool_); break; } case 354: { - input.ReadStringArray(tag, repeatedString_); + input.ReadStringArray(repeatedString_); break; } case 362: { - input.ReadBytesArray(tag, repeatedBytes_); + input.ReadBytesArray(repeatedBytes_); break; } case 386: { - input.ReadMessageArray(tag, repeatedNestedMessage_, global::Google.Protobuf.TestProtos.TestAllTypes.Types.NestedMessage.Parser); + input.ReadMessageArray(repeatedNestedMessage_, global::Google.Protobuf.TestProtos.TestAllTypes.Types.NestedMessage.Parser); break; } case 394: { - input.ReadMessageArray(tag, repeatedForeignMessage_, global::Google.Protobuf.TestProtos.ForeignMessage.Parser); + input.ReadMessageArray(repeatedForeignMessage_, global::Google.Protobuf.TestProtos.ForeignMessage.Parser); break; } case 402: { - input.ReadMessageArray(tag, repeatedImportMessage_, global::Google.Protobuf.TestProtos.ImportMessage.Parser); + input.ReadMessageArray(repeatedImportMessage_, global::Google.Protobuf.TestProtos.ImportMessage.Parser); break; } case 410: case 408: { - input.ReadEnumArray(tag, repeatedNestedEnum_); + input.ReadEnumArray(repeatedNestedEnum_); break; } case 418: case 416: { - input.ReadEnumArray(tag, repeatedForeignEnum_); + input.ReadEnumArray(repeatedForeignEnum_); break; } case 426: case 424: { - input.ReadEnumArray(tag, repeatedImportEnum_); + input.ReadEnumArray(repeatedImportEnum_); break; } case 434: { - input.ReadMessageArray(tag, repeatedPublicImportMessage_, global::Google.Protobuf.TestProtos.PublicImportMessage.Parser); + input.ReadMessageArray(repeatedPublicImportMessage_, global::Google.Protobuf.TestProtos.PublicImportMessage.Parser); break; } case 888: { @@ -1919,7 +1919,7 @@ namespace Google.Protobuf.TestProtos { break; } case 26: { - input.ReadMessageArray(tag, repeatedChild_, global::Google.Protobuf.TestProtos.NestedTestAllTypes.Parser); + input.ReadMessageArray(repeatedChild_, global::Google.Protobuf.TestProtos.NestedTestAllTypes.Parser); break; } } @@ -2973,20 +2973,20 @@ namespace Google.Protobuf.TestProtos { } case 58: case 56: { - input.ReadInt32Array(tag, repeatedPrimitiveField_); + input.ReadInt32Array(repeatedPrimitiveField_); break; } case 66: { - input.ReadStringArray(tag, repeatedStringField_); + input.ReadStringArray(repeatedStringField_); break; } case 74: case 72: { - input.ReadEnumArray(tag, repeatedEnumField_); + input.ReadEnumArray(repeatedEnumField_); break; } case 82: { - input.ReadMessageArray(tag, repeatedMessageField_, global::Google.Protobuf.TestProtos.ForeignMessage.Parser); + input.ReadMessageArray(repeatedMessageField_, global::Google.Protobuf.TestProtos.ForeignMessage.Parser); break; } } @@ -3552,7 +3552,7 @@ namespace Google.Protobuf.TestProtos { } break; case 10: { - input.ReadStringArray(tag, data_); + input.ReadStringArray(data_); break; } } @@ -4716,72 +4716,72 @@ namespace Google.Protobuf.TestProtos { break; case 722: case 720: { - input.ReadInt32Array(tag, packedInt32_); + input.ReadInt32Array(packedInt32_); break; } case 730: case 728: { - input.ReadInt64Array(tag, packedInt64_); + input.ReadInt64Array(packedInt64_); break; } case 738: case 736: { - input.ReadUInt32Array(tag, packedUint32_); + input.ReadUInt32Array(packedUint32_); break; } case 746: case 744: { - input.ReadUInt64Array(tag, packedUint64_); + input.ReadUInt64Array(packedUint64_); break; } case 754: case 752: { - input.ReadSInt32Array(tag, packedSint32_); + input.ReadSInt32Array(packedSint32_); break; } case 762: case 760: { - input.ReadSInt64Array(tag, packedSint64_); + input.ReadSInt64Array(packedSint64_); break; } case 770: case 773: { - input.ReadFixed32Array(tag, packedFixed32_); + input.ReadFixed32Array(packedFixed32_); break; } case 778: case 777: { - input.ReadFixed64Array(tag, packedFixed64_); + input.ReadFixed64Array(packedFixed64_); break; } case 786: case 789: { - input.ReadSFixed32Array(tag, packedSfixed32_); + input.ReadSFixed32Array(packedSfixed32_); break; } case 794: case 793: { - input.ReadSFixed64Array(tag, packedSfixed64_); + input.ReadSFixed64Array(packedSfixed64_); break; } case 802: case 805: { - input.ReadFloatArray(tag, packedFloat_); + input.ReadFloatArray(packedFloat_); break; } case 810: case 809: { - input.ReadDoubleArray(tag, packedDouble_); + input.ReadDoubleArray(packedDouble_); break; } case 818: case 816: { - input.ReadBoolArray(tag, packedBool_); + input.ReadBoolArray(packedBool_); break; } case 826: case 824: { - input.ReadEnumArray(tag, packedEnum_); + input.ReadEnumArray(packedEnum_); break; } } @@ -5120,72 +5120,72 @@ namespace Google.Protobuf.TestProtos { break; case 722: case 720: { - input.ReadInt32Array(tag, unpackedInt32_); + input.ReadInt32Array(unpackedInt32_); break; } case 730: case 728: { - input.ReadInt64Array(tag, unpackedInt64_); + input.ReadInt64Array(unpackedInt64_); break; } case 738: case 736: { - input.ReadUInt32Array(tag, unpackedUint32_); + input.ReadUInt32Array(unpackedUint32_); break; } case 746: case 744: { - input.ReadUInt64Array(tag, unpackedUint64_); + input.ReadUInt64Array(unpackedUint64_); break; } case 754: case 752: { - input.ReadSInt32Array(tag, unpackedSint32_); + input.ReadSInt32Array(unpackedSint32_); break; } case 762: case 760: { - input.ReadSInt64Array(tag, unpackedSint64_); + input.ReadSInt64Array(unpackedSint64_); break; } case 770: case 773: { - input.ReadFixed32Array(tag, unpackedFixed32_); + input.ReadFixed32Array(unpackedFixed32_); break; } case 778: case 777: { - input.ReadFixed64Array(tag, unpackedFixed64_); + input.ReadFixed64Array(unpackedFixed64_); break; } case 786: case 789: { - input.ReadSFixed32Array(tag, unpackedSfixed32_); + input.ReadSFixed32Array(unpackedSfixed32_); break; } case 794: case 793: { - input.ReadSFixed64Array(tag, unpackedSfixed64_); + input.ReadSFixed64Array(unpackedSfixed64_); break; } case 802: case 805: { - input.ReadFloatArray(tag, unpackedFloat_); + input.ReadFloatArray(unpackedFloat_); break; } case 810: case 809: { - input.ReadDoubleArray(tag, unpackedDouble_); + input.ReadDoubleArray(unpackedDouble_); break; } case 818: case 816: { - input.ReadBoolArray(tag, unpackedBool_); + input.ReadBoolArray(unpackedBool_); break; } case 826: case 824: { - input.ReadEnumArray(tag, unpackedEnum_); + input.ReadEnumArray(unpackedEnum_); break; } } @@ -5378,32 +5378,32 @@ namespace Google.Protobuf.TestProtos { break; case 98: case 101: { - input.ReadFixed32Array(tag, repeatedFixed32_); + input.ReadFixed32Array(repeatedFixed32_); break; } case 106: case 104: { - input.ReadInt32Array(tag, repeatedInt32_); + input.ReadInt32Array(repeatedInt32_); break; } case 16370: case 16369: { - input.ReadFixed64Array(tag, repeatedFixed64_); + input.ReadFixed64Array(repeatedFixed64_); break; } case 16378: case 16376: { - input.ReadInt64Array(tag, repeatedInt64_); + input.ReadInt64Array(repeatedInt64_); break; } case 2097138: case 2097141: { - input.ReadFloatArray(tag, repeatedFloat_); + input.ReadFloatArray(repeatedFloat_); break; } case 2097146: case 2097144: { - input.ReadUInt64Array(tag, repeatedUint64_); + input.ReadUInt64Array(repeatedUint64_); break; } } diff --git a/csharp/src/ProtocolBuffers/ByteArray.cs b/csharp/src/ProtocolBuffers/ByteArray.cs index d367fc39..211a0e11 100644 --- a/csharp/src/ProtocolBuffers/ByteArray.cs +++ b/csharp/src/ProtocolBuffers/ByteArray.cs @@ -51,7 +51,7 @@ namespace Google.Protobuf /// /// Determines which copy routine to use based on the number of bytes to be copied. /// - public static void Copy(byte[] src, int srcOffset, byte[] dst, int dstOffset, int count) + internal static void Copy(byte[] src, int srcOffset, byte[] dst, int dstOffset, int count) { if (count > CopyThreshold) { @@ -66,7 +66,7 @@ namespace Google.Protobuf /// /// Copy the bytes provided with a for loop, faster when there are only a few bytes to copy /// - public static void ByteCopy(byte[] src, int srcOffset, byte[] dst, int dstOffset, int count) + internal static void ByteCopy(byte[] src, int srcOffset, byte[] dst, int dstOffset, int count) { int stop = srcOffset + count; for (int i = srcOffset; i < stop; i++) @@ -78,12 +78,11 @@ namespace Google.Protobuf /// /// Reverses the order of bytes in the array /// - public static void Reverse(byte[] bytes) + internal static void Reverse(byte[] bytes) { - byte temp; for (int first = 0, last = bytes.Length - 1; first < last; first++, last--) { - temp = bytes[first]; + byte temp = bytes[first]; bytes[first] = bytes[last]; bytes[last] = temp; } diff --git a/csharp/src/ProtocolBuffers/CodedInputStream.cs b/csharp/src/ProtocolBuffers/CodedInputStream.cs index 56283318..905cdb9d 100644 --- a/csharp/src/ProtocolBuffers/CodedInputStream.cs +++ b/csharp/src/ProtocolBuffers/CodedInputStream.cs @@ -37,9 +37,7 @@ using System; using System.Collections.Generic; using System.IO; -using System.Text; using Google.Protobuf.Collections; -using Google.Protobuf.Descriptors; namespace Google.Protobuf { @@ -183,7 +181,7 @@ namespace Google.Protobuf /// /// The last /// tag read was not the one specified - public void CheckLastTagWas(uint value) + internal void CheckLastTagWas(uint value) { if (lastTag != value) { @@ -251,7 +249,7 @@ namespace Google.Protobuf /// public double ReadDouble() { - return FrameworkPortability.Int64ToDouble((long) ReadRawLittleEndian64()); + return BitConverter.Int64BitsToDouble((long) ReadRawLittleEndian64()); } /// @@ -347,21 +345,6 @@ namespace Google.Protobuf return CodedOutputStream.Utf8Encoding.GetString(ReadRawBytes(size), 0, size); } - /// - /// Reads a group field value from the stream. - /// - public void ReadGroup(int fieldNumber, IMessage message) - { - if (recursionDepth >= recursionLimit) - { - throw InvalidProtocolBufferException.RecursionLimitExceeded(); - } - ++recursionDepth; - message.MergeFrom(this); - CheckLastTagWas(WireFormat.MakeTag(fieldNumber, WireFormat.WireType.EndGroup)); - --recursionDepth; - } - /// /// Reads an embedded message field value from the stream. /// @@ -516,24 +499,34 @@ namespace Google.Protobuf return false; } - public void ReadStringArray(uint fieldTag, ICollection list) + /// + /// Reads a string array. + /// + /// The stream is assumed to be positioned after a tag indicating the field + /// repeated string value. A string is read, and then if the next tag is the same, + /// the process is repeated, until the next tag is a different one. + /// + public void ReadStringArray(ICollection list) { + uint fieldTag = lastTag; do { list.Add(ReadString()); } while (ContinueArray(fieldTag)); } - public void ReadBytesArray(uint fieldTag, ICollection list) + public void ReadBytesArray(ICollection list) { + uint fieldTag = lastTag; do { list.Add(ReadBytes()); } while (ContinueArray(fieldTag)); } - public void ReadBoolArray(uint fieldTag, ICollection list) + public void ReadBoolArray(ICollection list) { + uint fieldTag = lastTag; bool isPacked; int holdLimit; if (BeginArray(fieldTag, out isPacked, out holdLimit)) @@ -545,8 +538,9 @@ namespace Google.Protobuf } } - public void ReadInt32Array(uint fieldTag, ICollection list) + public void ReadInt32Array(ICollection list) { + uint fieldTag = lastTag; bool isPacked; int holdLimit; if (BeginArray(fieldTag, out isPacked, out holdLimit)) @@ -558,8 +552,9 @@ namespace Google.Protobuf } } - public void ReadSInt32Array(uint fieldTag, ICollection list) + public void ReadSInt32Array(ICollection list) { + uint fieldTag = lastTag; bool isPacked; int holdLimit; if (BeginArray(fieldTag, out isPacked, out holdLimit)) @@ -571,8 +566,9 @@ namespace Google.Protobuf } } - public void ReadUInt32Array(uint fieldTag, ICollection list) + public void ReadUInt32Array(ICollection list) { + uint fieldTag = lastTag; bool isPacked; int holdLimit; if (BeginArray(fieldTag, out isPacked, out holdLimit)) @@ -584,8 +580,9 @@ namespace Google.Protobuf } } - public void ReadFixed32Array(uint fieldTag, ICollection list) + public void ReadFixed32Array(ICollection list) { + uint fieldTag = lastTag; bool isPacked; int holdLimit; if (BeginArray(fieldTag, out isPacked, out holdLimit)) @@ -597,8 +594,9 @@ namespace Google.Protobuf } } - public void ReadSFixed32Array(uint fieldTag, ICollection list) + public void ReadSFixed32Array(ICollection list) { + uint fieldTag = lastTag; bool isPacked; int holdLimit; if (BeginArray(fieldTag, out isPacked, out holdLimit)) @@ -610,8 +608,9 @@ namespace Google.Protobuf } } - public void ReadInt64Array(uint fieldTag, ICollection list) + public void ReadInt64Array(ICollection list) { + uint fieldTag = lastTag; bool isPacked; int holdLimit; if (BeginArray(fieldTag, out isPacked, out holdLimit)) @@ -623,8 +622,9 @@ namespace Google.Protobuf } } - public void ReadSInt64Array(uint fieldTag, ICollection list) + public void ReadSInt64Array(ICollection list) { + uint fieldTag = lastTag; bool isPacked; int holdLimit; if (BeginArray(fieldTag, out isPacked, out holdLimit)) @@ -636,8 +636,9 @@ namespace Google.Protobuf } } - public void ReadUInt64Array(uint fieldTag, ICollection list) + public void ReadUInt64Array(ICollection list) { + uint fieldTag = lastTag; bool isPacked; int holdLimit; if (BeginArray(fieldTag, out isPacked, out holdLimit)) @@ -649,8 +650,9 @@ namespace Google.Protobuf } } - public void ReadFixed64Array(uint fieldTag, ICollection list) + public void ReadFixed64Array(ICollection list) { + uint fieldTag = lastTag; bool isPacked; int holdLimit; if (BeginArray(fieldTag, out isPacked, out holdLimit)) @@ -662,8 +664,9 @@ namespace Google.Protobuf } } - public void ReadSFixed64Array(uint fieldTag, ICollection list) + public void ReadSFixed64Array(ICollection list) { + uint fieldTag = lastTag; bool isPacked; int holdLimit; if (BeginArray(fieldTag, out isPacked, out holdLimit)) @@ -675,8 +678,9 @@ namespace Google.Protobuf } } - public void ReadDoubleArray(uint fieldTag, ICollection list) + public void ReadDoubleArray(ICollection list) { + uint fieldTag = lastTag; bool isPacked; int holdLimit; if (BeginArray(fieldTag, out isPacked, out holdLimit)) @@ -688,8 +692,9 @@ namespace Google.Protobuf } } - public void ReadFloatArray(uint fieldTag, ICollection list) + public void ReadFloatArray(ICollection list) { + uint fieldTag = lastTag; bool isPacked; int holdLimit; if (BeginArray(fieldTag, out isPacked, out holdLimit)) @@ -701,9 +706,10 @@ namespace Google.Protobuf } } - public void ReadEnumArray(uint fieldTag, RepeatedField list) + public void ReadEnumArray(RepeatedField list) where T : struct, IComparable, IFormattable { + uint fieldTag = lastTag; WireFormat.WireType wformat = WireFormat.GetTagWireType(fieldTag); // 2.3 allows packed form even if the field is not declared packed. @@ -727,9 +733,10 @@ namespace Google.Protobuf } } - public void ReadMessageArray(uint fieldTag, ICollection list, MessageParser messageParser) + public void ReadMessageArray(ICollection list, MessageParser messageParser) where T : IMessage { + uint fieldTag = lastTag; do { T message = messageParser.CreateTemplate(); @@ -737,17 +744,6 @@ namespace Google.Protobuf list.Add(message); } while (ContinueArray(fieldTag)); } - - public void ReadGroupArray(uint fieldTag, ICollection list, MessageParser messageParser) - where T : IMessage - { - do - { - T message = messageParser.CreateTemplate(); - ReadGroup(WireFormat.GetTagFieldNumber(fieldTag), message); - list.Add(message); - } while (ContinueArray(fieldTag)); - } #endregion #region Underlying reading primitives diff --git a/csharp/src/ProtocolBuffers/CodedOutputStream.cs b/csharp/src/ProtocolBuffers/CodedOutputStream.cs index 1e6e7e55..e56ce789 100644 --- a/csharp/src/ProtocolBuffers/CodedOutputStream.cs +++ b/csharp/src/ProtocolBuffers/CodedOutputStream.cs @@ -35,12 +35,9 @@ #endregion using System; -using System.Collections; using System.IO; -using System.Linq; using System.Text; using Google.Protobuf.Collections; -using Google.Protobuf.Descriptors; namespace Google.Protobuf { @@ -151,7 +148,7 @@ namespace Google.Protobuf /// public void WriteDouble(double value) { - WriteRawLittleEndian64((ulong)FrameworkPortability.DoubleToInt64(value)); + WriteRawLittleEndian64((ulong)BitConverter.DoubleToInt64Bits(value)); } /// diff --git a/csharp/src/ProtocolBuffers/DescriptorProtos/DescriptorProtoFile.cs b/csharp/src/ProtocolBuffers/DescriptorProtos/DescriptorProtoFile.cs index 67938260..7b7abd8e 100644 --- a/csharp/src/ProtocolBuffers/DescriptorProtos/DescriptorProtoFile.cs +++ b/csharp/src/ProtocolBuffers/DescriptorProtos/DescriptorProtoFile.cs @@ -358,7 +358,7 @@ namespace Google.Protobuf.DescriptorProtos { } break; case 10: { - input.ReadMessageArray(tag, file_, global::Google.Protobuf.DescriptorProtos.FileDescriptorProto.Parser); + input.ReadMessageArray(file_, global::Google.Protobuf.DescriptorProtos.FileDescriptorProto.Parser); break; } } @@ -672,23 +672,23 @@ namespace Google.Protobuf.DescriptorProtos { break; } case 26: { - input.ReadStringArray(tag, dependency_); + input.ReadStringArray(dependency_); break; } case 34: { - input.ReadMessageArray(tag, messageType_, global::Google.Protobuf.DescriptorProtos.DescriptorProto.Parser); + input.ReadMessageArray(messageType_, global::Google.Protobuf.DescriptorProtos.DescriptorProto.Parser); break; } case 42: { - input.ReadMessageArray(tag, enumType_, global::Google.Protobuf.DescriptorProtos.EnumDescriptorProto.Parser); + input.ReadMessageArray(enumType_, global::Google.Protobuf.DescriptorProtos.EnumDescriptorProto.Parser); break; } case 50: { - input.ReadMessageArray(tag, service_, global::Google.Protobuf.DescriptorProtos.ServiceDescriptorProto.Parser); + input.ReadMessageArray(service_, global::Google.Protobuf.DescriptorProtos.ServiceDescriptorProto.Parser); break; } case 58: { - input.ReadMessageArray(tag, extension_, global::Google.Protobuf.DescriptorProtos.FieldDescriptorProto.Parser); + input.ReadMessageArray(extension_, global::Google.Protobuf.DescriptorProtos.FieldDescriptorProto.Parser); break; } case 66: { @@ -707,12 +707,12 @@ namespace Google.Protobuf.DescriptorProtos { } case 82: case 80: { - input.ReadInt32Array(tag, publicDependency_); + input.ReadInt32Array(publicDependency_); break; } case 90: case 88: { - input.ReadInt32Array(tag, weakDependency_); + input.ReadInt32Array(weakDependency_); break; } case 98: { @@ -979,23 +979,23 @@ namespace Google.Protobuf.DescriptorProtos { break; } case 18: { - input.ReadMessageArray(tag, field_, global::Google.Protobuf.DescriptorProtos.FieldDescriptorProto.Parser); + input.ReadMessageArray(field_, global::Google.Protobuf.DescriptorProtos.FieldDescriptorProto.Parser); break; } case 26: { - input.ReadMessageArray(tag, nestedType_, global::Google.Protobuf.DescriptorProtos.DescriptorProto.Parser); + input.ReadMessageArray(nestedType_, global::Google.Protobuf.DescriptorProtos.DescriptorProto.Parser); break; } case 34: { - input.ReadMessageArray(tag, enumType_, global::Google.Protobuf.DescriptorProtos.EnumDescriptorProto.Parser); + input.ReadMessageArray(enumType_, global::Google.Protobuf.DescriptorProtos.EnumDescriptorProto.Parser); break; } case 42: { - input.ReadMessageArray(tag, extensionRange_, global::Google.Protobuf.DescriptorProtos.DescriptorProto.Types.ExtensionRange.Parser); + input.ReadMessageArray(extensionRange_, global::Google.Protobuf.DescriptorProtos.DescriptorProto.Types.ExtensionRange.Parser); break; } case 50: { - input.ReadMessageArray(tag, extension_, global::Google.Protobuf.DescriptorProtos.FieldDescriptorProto.Parser); + input.ReadMessageArray(extension_, global::Google.Protobuf.DescriptorProtos.FieldDescriptorProto.Parser); break; } case 58: { @@ -1006,15 +1006,15 @@ namespace Google.Protobuf.DescriptorProtos { break; } case 66: { - input.ReadMessageArray(tag, oneofDecl_, global::Google.Protobuf.DescriptorProtos.OneofDescriptorProto.Parser); + input.ReadMessageArray(oneofDecl_, global::Google.Protobuf.DescriptorProtos.OneofDescriptorProto.Parser); break; } case 74: { - input.ReadMessageArray(tag, reservedRange_, global::Google.Protobuf.DescriptorProtos.DescriptorProto.Types.ReservedRange.Parser); + input.ReadMessageArray(reservedRange_, global::Google.Protobuf.DescriptorProtos.DescriptorProto.Types.ReservedRange.Parser); break; } case 82: { - input.ReadStringArray(tag, reservedName_); + input.ReadStringArray(reservedName_); break; } } @@ -1800,7 +1800,7 @@ namespace Google.Protobuf.DescriptorProtos { break; } case 18: { - input.ReadMessageArray(tag, value_, global::Google.Protobuf.DescriptorProtos.EnumValueDescriptorProto.Parser); + input.ReadMessageArray(value_, global::Google.Protobuf.DescriptorProtos.EnumValueDescriptorProto.Parser); break; } case 26: { @@ -2086,7 +2086,7 @@ namespace Google.Protobuf.DescriptorProtos { break; } case 18: { - input.ReadMessageArray(tag, method_, global::Google.Protobuf.DescriptorProtos.MethodDescriptorProto.Parser); + input.ReadMessageArray(method_, global::Google.Protobuf.DescriptorProtos.MethodDescriptorProto.Parser); break; } case 26: { @@ -2735,7 +2735,7 @@ namespace Google.Protobuf.DescriptorProtos { break; } case 7994: { - input.ReadMessageArray(tag, uninterpretedOption_, global::Google.Protobuf.DescriptorProtos.UninterpretedOption.Parser); + input.ReadMessageArray(uninterpretedOption_, global::Google.Protobuf.DescriptorProtos.UninterpretedOption.Parser); break; } } @@ -2933,7 +2933,7 @@ namespace Google.Protobuf.DescriptorProtos { break; } case 7994: { - input.ReadMessageArray(tag, uninterpretedOption_, global::Google.Protobuf.DescriptorProtos.UninterpretedOption.Parser); + input.ReadMessageArray(uninterpretedOption_, global::Google.Protobuf.DescriptorProtos.UninterpretedOption.Parser); break; } } @@ -3167,7 +3167,7 @@ namespace Google.Protobuf.DescriptorProtos { break; } case 7994: { - input.ReadMessageArray(tag, uninterpretedOption_, global::Google.Protobuf.DescriptorProtos.UninterpretedOption.Parser); + input.ReadMessageArray(uninterpretedOption_, global::Google.Protobuf.DescriptorProtos.UninterpretedOption.Parser); break; } } @@ -3323,7 +3323,7 @@ namespace Google.Protobuf.DescriptorProtos { break; } case 7994: { - input.ReadMessageArray(tag, uninterpretedOption_, global::Google.Protobuf.DescriptorProtos.UninterpretedOption.Parser); + input.ReadMessageArray(uninterpretedOption_, global::Google.Protobuf.DescriptorProtos.UninterpretedOption.Parser); break; } } @@ -3437,7 +3437,7 @@ namespace Google.Protobuf.DescriptorProtos { break; } case 7994: { - input.ReadMessageArray(tag, uninterpretedOption_, global::Google.Protobuf.DescriptorProtos.UninterpretedOption.Parser); + input.ReadMessageArray(uninterpretedOption_, global::Google.Protobuf.DescriptorProtos.UninterpretedOption.Parser); break; } } @@ -3551,7 +3551,7 @@ namespace Google.Protobuf.DescriptorProtos { break; } case 7994: { - input.ReadMessageArray(tag, uninterpretedOption_, global::Google.Protobuf.DescriptorProtos.UninterpretedOption.Parser); + input.ReadMessageArray(uninterpretedOption_, global::Google.Protobuf.DescriptorProtos.UninterpretedOption.Parser); break; } } @@ -3665,7 +3665,7 @@ namespace Google.Protobuf.DescriptorProtos { break; } case 7994: { - input.ReadMessageArray(tag, uninterpretedOption_, global::Google.Protobuf.DescriptorProtos.UninterpretedOption.Parser); + input.ReadMessageArray(uninterpretedOption_, global::Google.Protobuf.DescriptorProtos.UninterpretedOption.Parser); break; } } @@ -3875,7 +3875,7 @@ namespace Google.Protobuf.DescriptorProtos { } break; case 18: { - input.ReadMessageArray(tag, name_, global::Google.Protobuf.DescriptorProtos.UninterpretedOption.Types.NamePart.Parser); + input.ReadMessageArray(name_, global::Google.Protobuf.DescriptorProtos.UninterpretedOption.Types.NamePart.Parser); break; } case 26: { @@ -4111,7 +4111,7 @@ namespace Google.Protobuf.DescriptorProtos { } break; case 10: { - input.ReadMessageArray(tag, location_, global::Google.Protobuf.DescriptorProtos.SourceCodeInfo.Types.Location.Parser); + input.ReadMessageArray(location_, global::Google.Protobuf.DescriptorProtos.SourceCodeInfo.Types.Location.Parser); break; } } @@ -4287,12 +4287,12 @@ namespace Google.Protobuf.DescriptorProtos { break; case 10: case 8: { - input.ReadInt32Array(tag, path_); + input.ReadInt32Array(path_); break; } case 18: case 16: { - input.ReadInt32Array(tag, span_); + input.ReadInt32Array(span_); break; } case 26: { @@ -4304,7 +4304,7 @@ namespace Google.Protobuf.DescriptorProtos { break; } case 50: { - input.ReadStringArray(tag, leadingDetachedComments_); + input.ReadStringArray(leadingDetachedComments_); break; } } diff --git a/csharp/src/ProtocolBuffers/Extensions.cs b/csharp/src/ProtocolBuffers/Extensions.cs deleted file mode 100644 index 7f23057e..00000000 --- a/csharp/src/ProtocolBuffers/Extensions.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System.IO; - -namespace Google.Protobuf -{ - // TODO: MessageExtensions? - public static class Extensions - { - public static void MergeFrom(this IMessage message, byte[] data) - { - CodedInputStream input = CodedInputStream.CreateInstance(data); - message.MergeFrom(input); - input.CheckLastTagWas(0); - } - - public static void MergeFrom(this IMessage message, ByteString data) - { - CodedInputStream input = data.CreateCodedInput(); - message.MergeFrom(input); - input.CheckLastTagWas(0); - } - - public static void MergeFrom(this IMessage message, Stream input) - { - CodedInputStream codedInput = CodedInputStream.CreateInstance(input); - message.MergeFrom(codedInput); - codedInput.CheckLastTagWas(0); - } - - public static void MergeDelimitedFrom(this IMessage message, Stream input) - { - int size = (int)CodedInputStream.ReadRawVarint32(input); - Stream limitedStream = new LimitedInputStream(input, size); - message.MergeFrom(limitedStream); - } - - public static byte[] ToByteArray(this IMessage message) - { - byte[] result = new byte[message.CalculateSize()]; - CodedOutputStream output = CodedOutputStream.CreateInstance(result); - message.WriteTo(output); - output.CheckNoSpaceLeft(); - return result; - } - - public static void WriteTo(this IMessage message, Stream output) - { - CodedOutputStream codedOutput = CodedOutputStream.CreateInstance(output); - message.WriteTo(codedOutput); - codedOutput.Flush(); - } - - public static void WriteTo(this IMessage message, CodedOutputStream output) - { - message.WriteTo(output); - } - - public static void WriteDelimitedTo(this IMessage message, Stream output) - { - CodedOutputStream codedOutput = CodedOutputStream.CreateInstance(output); - codedOutput.WriteRawVarint32((uint)message.CalculateSize()); - message.WriteTo(codedOutput); - codedOutput.Flush(); - } - - public static ByteString ToByteString(this IMessage message) - { - return ByteString.AttachBytes(message.ToByteArray()); - } - } -} diff --git a/csharp/src/ProtocolBuffers/FrameworkPortability.cs b/csharp/src/ProtocolBuffers/FrameworkPortability.cs index 5fa7c4e7..06246a9e 100644 --- a/csharp/src/ProtocolBuffers/FrameworkPortability.cs +++ b/csharp/src/ProtocolBuffers/FrameworkPortability.cs @@ -35,8 +35,6 @@ #endregion using System; -using System.Globalization; -using System.Reflection; using System.Text.RegularExpressions; namespace Google.Protobuf @@ -46,66 +44,10 @@ namespace Google.Protobuf /// internal static class FrameworkPortability { -#if COMPACT_FRAMEWORK - internal const string NewLine = "\n"; -#else - internal static readonly string NewLine = System.Environment.NewLine; -#endif - -#if CLIENTPROFILE - internal const RegexOptions CompiledRegexWhereAvailable = RegexOptions.Compiled; -#else - internal const RegexOptions CompiledRegexWhereAvailable = RegexOptions.None; -#endif - - internal static CultureInfo InvariantCulture - { - get { return CultureInfo.InvariantCulture; } - } - - internal static double Int64ToDouble(long value) - { -#if CLIENTPROFILE - return BitConverter.Int64BitsToDouble(value); -#else - double[] arresult = new double[1]; - Buffer.BlockCopy(new[] { value }, 0, arresult, 0, 8); - return arresult[0]; -#endif - } - - internal static long DoubleToInt64(double value) - { -#if CLIENTPROFILE - return BitConverter.DoubleToInt64Bits(value); -#else - long[] arresult = new long[1]; - Buffer.BlockCopy(new[] { value }, 0, arresult, 0, 8); - return arresult[0]; -#endif - } - - internal static bool TryParseInt32(string text, out int number) - { - return TryParseInt32(text, NumberStyles.Any, InvariantCulture, out number); - } - - internal static bool TryParseInt32(string text, NumberStyles style, IFormatProvider format, out int number) - { -#if COMPACT_FRAMEWORK - try - { - number = int.Parse(text, style, format); - return true; - } - catch - { - number = 0; - return false; - } -#else - return int.TryParse(text, style, format, out number); -#endif - } + // The value of RegexOptions.Compiled is 8. We can test for the presence at + // execution time using Enum.IsDefined, so a single build will do the right thing + // on each platform. + internal static readonly RegexOptions CompiledRegexWhereAvailable = + Enum.IsDefined(typeof(RegexOptions), 8) ? (RegexOptions)8 : RegexOptions.None; } } \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers/IMessage.cs b/csharp/src/ProtocolBuffers/IMessage.cs index 55b6fc5d..9c2a2d85 100644 --- a/csharp/src/ProtocolBuffers/IMessage.cs +++ b/csharp/src/ProtocolBuffers/IMessage.cs @@ -34,30 +34,63 @@ #endregion -using System; -using System.Collections.Generic; -using System.IO; -using Google.Protobuf.Descriptors; using Google.Protobuf.FieldAccess; namespace Google.Protobuf { - // TODO(jonskeet): Do we want a "weak" version of IReflectedMessage? + // TODO(jonskeet): Do we want a "weak" (non-generic) version of IReflectedMessage? + + /// + /// Reflection support for a specific message type. message + /// + /// The message type being reflected. public interface IReflectedMessage where T : IMessage { FieldAccessorTable Fields { get; } + // TODO(jonskeet): Descriptor? Or a single property which has "all you need for reflection"? } + /// + /// Interface for a Protocol Buffers message, supporting + /// basic operations required for serialization. + /// public interface IMessage { + /// + /// Merges the data from the specified coded input stream with the current message. + /// + /// See the user guide for precise merge semantics. + /// void MergeFrom(CodedInputStream input); + + /// + /// Writes the data to the given coded output stream. + /// + /// Coded output stream to write the data to. Must not be null. void WriteTo(CodedOutputStream output); + + /// + /// Calculates the size of this message in Protocol Buffer wire format, in bytes. + /// + /// The number of bytes required to write this message + /// to a coded output stream. int CalculateSize(); } + /// + /// Generic interface for a Protocol Buffers message, + /// where the type parameter is expected to be the same type as + /// the implementation class. + /// + /// The message type. public interface IMessage : IMessage where T : IMessage { + /// + /// Merges the given message into this one. + /// + /// See the user guide for precise merge semantics. + /// The message to merge with this one. Must not be null. void MergeFrom(T message); } } \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers/MessageExtensions.cs b/csharp/src/ProtocolBuffers/MessageExtensions.cs new file mode 100644 index 00000000..57cecfd4 --- /dev/null +++ b/csharp/src/ProtocolBuffers/MessageExtensions.cs @@ -0,0 +1,81 @@ +using System.IO; + +namespace Google.Protobuf +{ + /// + /// Extension methods on and . + /// + public static class MessageExtensions + { + public static void MergeFrom(this IMessage message, byte[] data) + { + ThrowHelper.ThrowIfNull(message, "message"); + ThrowHelper.ThrowIfNull(data, "data"); + CodedInputStream input = CodedInputStream.CreateInstance(data); + message.MergeFrom(input); + input.CheckLastTagWas(0); + } + + public static void MergeFrom(this IMessage message, ByteString data) + { + ThrowHelper.ThrowIfNull(message, "message"); + ThrowHelper.ThrowIfNull(data, "data"); + CodedInputStream input = data.CreateCodedInput(); + message.MergeFrom(input); + input.CheckLastTagWas(0); + } + + public static void MergeFrom(this IMessage message, Stream input) + { + ThrowHelper.ThrowIfNull(message, "message"); + ThrowHelper.ThrowIfNull(input, "input"); + CodedInputStream codedInput = CodedInputStream.CreateInstance(input); + message.MergeFrom(codedInput); + codedInput.CheckLastTagWas(0); + } + + public static void MergeDelimitedFrom(this IMessage message, Stream input) + { + ThrowHelper.ThrowIfNull(message, "message"); + ThrowHelper.ThrowIfNull(input, "input"); + int size = (int)CodedInputStream.ReadRawVarint32(input); + Stream limitedStream = new LimitedInputStream(input, size); + message.MergeFrom(limitedStream); + } + + public static byte[] ToByteArray(this IMessage message) + { + ThrowHelper.ThrowIfNull(message, "message"); + byte[] result = new byte[message.CalculateSize()]; + CodedOutputStream output = CodedOutputStream.CreateInstance(result); + message.WriteTo(output); + output.CheckNoSpaceLeft(); + return result; + } + + public static void WriteTo(this IMessage message, Stream output) + { + ThrowHelper.ThrowIfNull(message, "message"); + ThrowHelper.ThrowIfNull(output, "output"); + CodedOutputStream codedOutput = CodedOutputStream.CreateInstance(output); + message.WriteTo(codedOutput); + codedOutput.Flush(); + } + + public static void WriteDelimitedTo(this IMessage message, Stream output) + { + ThrowHelper.ThrowIfNull(message, "message"); + ThrowHelper.ThrowIfNull(output, "output"); + CodedOutputStream codedOutput = CodedOutputStream.CreateInstance(output); + codedOutput.WriteRawVarint32((uint)message.CalculateSize()); + message.WriteTo(codedOutput); + codedOutput.Flush(); + } + + public static ByteString ToByteString(this IMessage message) + { + ThrowHelper.ThrowIfNull(message, "message"); + return ByteString.AttachBytes(message.ToByteArray()); + } + } +} diff --git a/csharp/src/ProtocolBuffers/MessageParser.cs b/csharp/src/ProtocolBuffers/MessageParser.cs index 722435cc..18cda2dc 100644 --- a/csharp/src/ProtocolBuffers/MessageParser.cs +++ b/csharp/src/ProtocolBuffers/MessageParser.cs @@ -1,26 +1,58 @@ using System; using System.IO; -using Google.Protobuf; namespace Google.Protobuf { + /// + /// A parser for a specific message type. + /// + /// + ///

+ /// This delegates most behavior to the + /// implementation within the original type, but + /// provides convenient overloads to parse from a variety of sources. + ///

+ ///

+ /// Most applications will never need to create their own instances of this type; + /// instead, use the static Parser property of a generated message type to obtain a + /// parser for that type. + ///

+ ///
+ /// The type of message to be parsed. public sealed class MessageParser where T : IMessage { private readonly Func factory; + /// + /// Creates a new parser. + /// + /// + /// The factory method is effectively an optimization over using a generic constraint + /// to require a parameterless constructor: delegates are significantly faster to execute. + /// + /// Function to invoke when a new, empty message is required. public MessageParser(Func factory) { this.factory = factory; } - // Creates a template instance ready for population. + /// + /// Creates a template instance ready for population. + /// + /// An empty message. internal T CreateTemplate() { return factory(); } + /// + /// Parses a message from a byte array. + /// + /// The byte array containing the message. Must not be null. + /// The newly parsed message. public T ParseFrom(byte[] data) { + ThrowHelper.ThrowIfNull(data, "data"); T message = factory(); message.MergeFrom(data); return message; @@ -28,6 +60,7 @@ namespace Google.Protobuf public T ParseFrom(ByteString data) { + ThrowHelper.ThrowIfNull(data, "data"); T message = factory(); message.MergeFrom(data); return message; diff --git a/csharp/src/ProtocolBuffers/ProtocolBuffers.csproj b/csharp/src/ProtocolBuffers/ProtocolBuffers.csproj index 3a07e87f..33a32ff2 100644 --- a/csharp/src/ProtocolBuffers/ProtocolBuffers.csproj +++ b/csharp/src/ProtocolBuffers/ProtocolBuffers.csproj @@ -84,7 +84,8 @@ - + + @@ -92,7 +93,6 @@ - diff --git a/csharp/src/ProtocolBuffers/ThrowHelper.cs b/csharp/src/ProtocolBuffers/ThrowHelper.cs index 097b5032..c12a48a3 100644 --- a/csharp/src/ProtocolBuffers/ThrowHelper.cs +++ b/csharp/src/ProtocolBuffers/ThrowHelper.cs @@ -42,12 +42,12 @@ namespace Google.Protobuf /// /// Helper methods for throwing exceptions /// - public static class ThrowHelper + internal static class ThrowHelper { /// /// Throws an ArgumentNullException if the given value is null. /// - public static void ThrowIfNull(object value, string name) + internal static void ThrowIfNull(object value, string name) { if (value == null) { @@ -58,7 +58,7 @@ namespace Google.Protobuf /// /// Throws an ArgumentNullException if the given value is null. /// - public static void ThrowIfNull(object value) + internal static void ThrowIfNull(object value) { if (value == null) { @@ -69,7 +69,7 @@ namespace Google.Protobuf /// /// Throws an ArgumentNullException if the given value or any element within it is null. /// - public static void ThrowIfAnyNull(IEnumerable sequence) + internal static void ThrowIfAnyNull(IEnumerable sequence) { foreach (T t in sequence) { @@ -79,14 +79,5 @@ namespace Google.Protobuf } } } - - public static Exception CreateMissingMethod(Type type, string methodName) - { -#if CLIENTPROFILE - return new System.MissingMethodException(type.FullName, methodName); -#else - return new System.ArgumentException(String.Format("The method '{0}' was not found on type {1}.", methodName, type)); -#endif - } } } \ No newline at end of file diff --git a/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc b/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc index c78aaef6..29c931e3 100644 --- a/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc @@ -76,7 +76,7 @@ void RepeatedEnumFieldGenerator::GenerateMergingCode(io::Printer* printer) { void RepeatedEnumFieldGenerator::GenerateParsingCode(io::Printer* printer) { printer->Print( variables_, - "input.ReadEnumArray<$type_name$>(tag, $name$_);\n"); + "input.ReadEnumArray<$type_name$>($name$_);\n"); } void RepeatedEnumFieldGenerator::GenerateSerializationCode(io::Printer* printer) { diff --git a/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc b/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc index 3553fe12..3ab0b190 100644 --- a/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc @@ -75,7 +75,7 @@ void RepeatedMessageFieldGenerator::GenerateMergingCode(io::Printer* printer) { void RepeatedMessageFieldGenerator::GenerateParsingCode(io::Printer* printer) { printer->Print( variables_, - "input.ReadMessageArray(tag, $name$_, $type_name$.Parser);\n"); + "input.ReadMessageArray($name$_, $type_name$.Parser);\n"); } void RepeatedMessageFieldGenerator::GenerateSerializationCode(io::Printer* printer) { diff --git a/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc b/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc index fe8a4364..cc787d50 100644 --- a/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc @@ -75,7 +75,7 @@ void RepeatedPrimitiveFieldGenerator::GenerateMergingCode(io::Printer* printer) void RepeatedPrimitiveFieldGenerator::GenerateParsingCode(io::Printer* printer) { printer->Print(variables_, - "input.Read$capitalized_type_name$Array(tag, $name$_);\n"); + "input.Read$capitalized_type_name$Array($name$_);\n"); } void RepeatedPrimitiveFieldGenerator::GenerateSerializationCode( -- cgit v1.2.3