diff --git a/.gitignore b/.gitignore index b359dea3b91b6..e17724693c5fb 100644 --- a/.gitignore +++ b/.gitignore @@ -79,8 +79,7 @@ java/target javanano/target # Windows native output. -vsprojects/Debug -vsprojects/Release +cmake/build # NuGet packages: we want the repository configuration, but not the # packages themselves. diff --git a/BUILD b/BUILD index 5177e43df3fab..5cfed337e67d2 100644 --- a/BUILD +++ b/BUILD @@ -162,10 +162,10 @@ cc_library( "src/google/protobuf/compiler/cpp/cpp_string_field.cc", "src/google/protobuf/compiler/csharp/csharp_enum.cc", "src/google/protobuf/compiler/csharp/csharp_enum_field.cc", - "src/google/protobuf/compiler/csharp/csharp_extension.cc", "src/google/protobuf/compiler/csharp/csharp_field_base.cc", "src/google/protobuf/compiler/csharp/csharp_generator.cc", "src/google/protobuf/compiler/csharp/csharp_helpers.cc", + "src/google/protobuf/compiler/csharp/csharp_map_field.cc", "src/google/protobuf/compiler/csharp/csharp_message.cc", "src/google/protobuf/compiler/csharp/csharp_message_field.cc", "src/google/protobuf/compiler/csharp/csharp_primitive_field.cc", @@ -174,7 +174,7 @@ cc_library( "src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc", "src/google/protobuf/compiler/csharp/csharp_source_generator_base.cc", "src/google/protobuf/compiler/csharp/csharp_umbrella_class.cc", - "src/google/protobuf/compiler/csharp/csharp_writer.cc", + "src/google/protobuf/compiler/csharp/csharp_wrapper_field.cc", "src/google/protobuf/compiler/java/java_context.cc", "src/google/protobuf/compiler/java/java_doc_comment.cc", "src/google/protobuf/compiler/java/java_enum.cc", diff --git a/Makefile.am b/Makefile.am index 3786200531ed7..fad35a0960455 100644 --- a/Makefile.am +++ b/Makefile.am @@ -40,254 +40,112 @@ clean-local: pkgconfigdir = $(libdir)/pkgconfig pkgconfig_DATA = protobuf.pc protobuf-lite.pc -csharp_EXTRA_DIST= \ - csharp/src/ProtocolBuffers.sln \ - csharp/src/ProtocolBuffersLite.Test/TestProtos/UnittestImportPublicLite.cs \ - csharp/src/ProtocolBuffersLite.Test/TestProtos/UnittestExtrasLite.cs \ - csharp/src/ProtocolBuffersLite.Test/TestProtos/UnittestExtrasFull.cs \ - csharp/src/ProtocolBuffersLite.Test/TestProtos/UnittestImport.cs \ - csharp/src/ProtocolBuffersLite.Test/TestProtos/UnittestLiteImportsNonlite.cs \ - csharp/src/ProtocolBuffersLite.Test/TestProtos/UnittestImportLite.cs \ - csharp/src/ProtocolBuffersLite.Test/TestProtos/Unittest.cs \ - csharp/src/ProtocolBuffersLite.Test/TestProtos/UnittestLite.cs \ - csharp/src/ProtocolBuffersLite.Test/TestProtos/UnittestImportPublic.cs \ - csharp/src/ProtocolBuffersLite.Test/ExtendableMessageLiteTest.cs \ - csharp/src/ProtocolBuffersLite.Test/packages.config \ - csharp/src/ProtocolBuffersLite.Test/LiteTest.cs \ - csharp/src/ProtocolBuffersLite.Test/AbstractMessageLiteTest.cs \ - csharp/src/ProtocolBuffersLite.Test/MissingFieldAndExtensionTest.cs \ - csharp/src/ProtocolBuffersLite.Test/ProtocolBuffersLite.Test.csproj \ - csharp/src/ProtocolBuffersLite.Test/App.xaml.cs \ - csharp/src/ProtocolBuffersLite.Test/InteropLiteTest.cs \ - csharp/src/ProtocolBuffersLite.Test/ExtendableBuilderLiteTest.cs \ - csharp/src/ProtocolBuffersLite.Test/App.xaml \ - csharp/src/ProtocolBuffersLite.Test/TestLiteByApi.cs \ - csharp/src/ProtocolBuffersLite.Test/Properties/AppManifest.xml \ - csharp/src/ProtocolBuffersLite.Test/Properties/OutOfBrowserSettings.xml \ - csharp/src/ProtocolBuffersLite.Test/ProtocolBuffersLiteMixed.Test.csproj \ - csharp/src/ProtocolBuffersLite.Test/AbstractBuilderLiteTest.cs \ - csharp/src/ProtoDump/ProtoDump.csproj \ - csharp/src/ProtoDump/app.config \ - csharp/src/ProtoDump/Program.cs \ - csharp/src/ProtoDump/Properties/AssemblyInfo.cs \ - csharp/src/ProtocolBuffers.Serialization/AbstractReader.cs \ - csharp/src/ProtocolBuffers.Serialization/JsonFormatReader.cs \ - csharp/src/ProtocolBuffers.Serialization/JsonTextCursor.cs \ - csharp/src/ProtocolBuffers.Serialization/ProtocolBuffers.Serialization.csproj \ - csharp/src/ProtocolBuffers.Serialization/DictionaryWriter.cs \ - csharp/src/ProtocolBuffers.Serialization/AbstractWriter.cs \ - csharp/src/ProtocolBuffers.Serialization/ProtocolBuffersLite.Serialization.csproj \ - csharp/src/ProtocolBuffers.Serialization/XmlReaderOptions.cs \ - csharp/src/ProtocolBuffers.Serialization/AbstractTextReader.cs \ - csharp/src/ProtocolBuffers.Serialization/XmlWriterOptions.cs \ - csharp/src/ProtocolBuffers.Serialization/JsonFormatWriter.cs \ - csharp/src/ProtocolBuffers.Serialization/Properties/AssemblyInfo.cs \ - csharp/src/ProtocolBuffers.Serialization/DictionaryReader.cs \ - csharp/src/ProtocolBuffers.Serialization/Extensions.cs \ - csharp/src/ProtocolBuffers.Serialization/AbstractTextWriter.cs \ - csharp/src/ProtocolBuffers.Serialization/XmlFormatWriter.cs \ - csharp/src/ProtocolBuffers.Serialization/Http/FormUrlEncodedReader.cs \ - csharp/src/ProtocolBuffers.Serialization/Http/MessageFormatOptions.cs \ - csharp/src/ProtocolBuffers.Serialization/Http/MessageFormatFactory.cs \ - csharp/src/ProtocolBuffers.Serialization/XmlFormatReader.cs \ - csharp/src/ProtocolBuffers.Serialization/RecursionLimitExceeded.cs \ - csharp/src/ProtoBench/GoogleSize.cs \ - csharp/src/ProtoBench/GoogleSpeed.cs \ - csharp/src/ProtoBench/UnittestImport.cs \ - csharp/src/ProtoBench/google_message1.dat \ - csharp/src/ProtoBench/ProtoBench.csproj \ - csharp/src/ProtoBench/app.config \ - csharp/src/ProtoBench/Program.cs \ - csharp/src/ProtoBench/google_message2.dat \ - csharp/src/ProtoBench/Properties/AssemblyInfo.cs \ - csharp/src/ProtoBench/Unittest.cs \ - csharp/src/ProtoBench/UnittestImportPublic.cs \ - csharp/src/ProtoMunge/app.config \ - csharp/src/ProtoMunge/Program.cs \ - csharp/src/ProtoMunge/Properties/AssemblyInfo.cs \ - csharp/src/ProtoMunge/ProtoMunge.csproj \ - csharp/src/ProtocolBuffers/GeneratedMessage.cs \ - csharp/src/ProtocolBuffers/ICodedInputStream.cs \ - csharp/src/ProtocolBuffers/AbstractBuilder.cs \ - csharp/src/ProtocolBuffers/FieldSet.cs \ - csharp/src/ProtocolBuffers/TextGenerator.cs \ - csharp/src/ProtocolBuffers/CodedInputStream.cs \ - csharp/src/ProtocolBuffers/GeneratedExtensionLite.cs \ - csharp/src/ProtocolBuffers/FrameworkPortability.cs \ - csharp/src/ProtocolBuffers/SortedList.cs \ - csharp/src/ProtocolBuffers/CodedOutputStream.ComputeSize.cs \ - csharp/src/ProtocolBuffers/ExtendableMessage.cs \ - csharp/src/ProtocolBuffers/Descriptors/ServiceDescriptor.cs \ - csharp/src/ProtocolBuffers/Descriptors/DescriptorBase.cs \ - csharp/src/ProtocolBuffers/Descriptors/EnumDescriptor.cs \ - csharp/src/ProtocolBuffers/Descriptors/PackageDescriptor.cs \ - csharp/src/ProtocolBuffers/Descriptors/FileDescriptor.cs \ - csharp/src/ProtocolBuffers/Descriptors/DescriptorValidationException.cs \ - csharp/src/ProtocolBuffers/Descriptors/IndexedDescriptorBase.cs \ - csharp/src/ProtocolBuffers/Descriptors/MessageDescriptor.cs \ - csharp/src/ProtocolBuffers/Descriptors/MethodDescriptor.cs \ - csharp/src/ProtocolBuffers/Descriptors/DescriptorUtil.cs \ - csharp/src/ProtocolBuffers/Descriptors/MappedType.cs \ - csharp/src/ProtocolBuffers/Descriptors/FieldType.cs \ - csharp/src/ProtocolBuffers/Descriptors/FieldMappingAttribute.cs \ - csharp/src/ProtocolBuffers/Descriptors/IDescriptor.cs \ - csharp/src/ProtocolBuffers/Descriptors/EnumValueDescriptor.cs \ - csharp/src/ProtocolBuffers/Descriptors/FieldDescriptor.cs \ - csharp/src/ProtocolBuffers/Descriptors/DescriptorPool.cs \ - csharp/src/ProtocolBuffers/Delegates.cs \ - csharp/src/ProtocolBuffers/AbstractMessageLite.cs \ - csharp/src/ProtocolBuffers/IMessageLite.cs \ - csharp/src/ProtocolBuffers/TextFormat.cs \ - csharp/src/ProtocolBuffers/Collections/Enumerables.cs \ - csharp/src/ProtocolBuffers/Collections/PopsicleList.cs \ - csharp/src/ProtocolBuffers/Collections/IPopsicleList.cs \ - csharp/src/ProtocolBuffers/Collections/ReadOnlyDictionary.cs \ - csharp/src/ProtocolBuffers/Collections/Dictionaries.cs \ - csharp/src/ProtocolBuffers/Collections/Lists.cs \ - csharp/src/ProtocolBuffers/IMessage.cs \ - csharp/src/ProtocolBuffers/TextTokenizer.cs \ - csharp/src/ProtocolBuffers/ByteString.cs \ - csharp/src/ProtocolBuffers/AbstractBuilderLite.cs \ - csharp/src/ProtocolBuffers/GeneratedExtensionBase.cs \ - csharp/src/ProtocolBuffers/EnumLite.cs \ - csharp/src/ProtocolBuffers/ByteArray.cs \ - csharp/src/ProtocolBuffers/ExtensionInfo.cs \ - csharp/src/ProtocolBuffers/MessageStreamIterator.cs \ - csharp/src/ProtocolBuffers/DynamicMessage.cs \ - csharp/src/ProtocolBuffers/ExtendableMessageLite.cs \ - csharp/src/ProtocolBuffers/ICodedOutputStream.cs \ - csharp/src/ProtocolBuffers/GeneratedRepeatExtension.cs \ - csharp/src/ProtocolBuffers/IBuilderLite.cs \ - csharp/src/ProtocolBuffers/UnknownField.cs \ - csharp/src/ProtocolBuffers/ThrowHelper.cs \ - csharp/src/ProtocolBuffers/UnknownFieldSet.cs \ - csharp/src/ProtocolBuffers/AbstractMessage.cs \ - csharp/src/ProtocolBuffers/GeneratedBuilderLite.cs \ - csharp/src/ProtocolBuffers/NameHelpers.cs \ - csharp/src/ProtocolBuffers/DescriptorProtos/PartialClasses.cs \ - csharp/src/ProtocolBuffers/DescriptorProtos/IDescriptorProto.cs \ - csharp/src/ProtocolBuffers/DescriptorProtos/DescriptorProtoFile.cs \ - csharp/src/ProtocolBuffers/ExtendableBuilder.cs \ - csharp/src/ProtocolBuffers/FieldAccess/IFieldAccessor.cs \ - csharp/src/ProtocolBuffers/FieldAccess/SinglePrimitiveAccessor.cs \ - csharp/src/ProtocolBuffers/FieldAccess/SingleEnumAccessor.cs \ - csharp/src/ProtocolBuffers/FieldAccess/RepeatedPrimitiveAccessor.cs \ - csharp/src/ProtocolBuffers/FieldAccess/FieldAccessorTable.cs \ - csharp/src/ProtocolBuffers/FieldAccess/RepeatedMessageAccessor.cs \ - csharp/src/ProtocolBuffers/FieldAccess/RepeatedEnumAccessor.cs \ - csharp/src/ProtocolBuffers/FieldAccess/ReflectionUtil.cs \ - csharp/src/ProtocolBuffers/FieldAccess/SingleMessageAccessor.cs \ - csharp/src/ProtocolBuffers/Properties/AssemblyInfo.cs \ - csharp/src/ProtocolBuffers/IBuilder.cs \ - csharp/src/ProtocolBuffers/ExtensionRegistry.cs \ - csharp/src/ProtocolBuffers/CodedOutputStream.cs \ - csharp/src/ProtocolBuffers/MessageStreamWriter.cs \ - csharp/src/ProtocolBuffers/MessageUtil.cs \ - csharp/src/ProtocolBuffers/UninitializedMessageException.cs \ - csharp/src/ProtocolBuffers/ProtocolBuffersLite.csproj \ - csharp/src/ProtocolBuffers/InvalidProtocolBufferException.cs \ - csharp/src/ProtocolBuffers/ProtocolBuffers.csproj \ - csharp/src/ProtocolBuffers/ExtendableBuilderLite.cs \ - csharp/src/ProtocolBuffers/GeneratedMessageLite.cs \ - csharp/src/ProtocolBuffers/GeneratedSingleExtension.cs \ - csharp/src/ProtocolBuffers/ExtensionRegistryLite.cs \ - csharp/src/ProtocolBuffers/WireFormat.cs \ - csharp/src/ProtocolBuffers/GeneratedBuilder.cs \ - csharp/src/AddressBook/ListPeople.cs \ - csharp/src/AddressBook/Addressbook.cs \ - csharp/src/AddressBook/AddPerson.cs \ - csharp/src/AddressBook/AddressBook.csproj \ - csharp/src/AddressBook/SampleUsage.cs \ - csharp/src/AddressBook/app.config \ - csharp/src/AddressBook/Program.cs \ - csharp/src/AddressBook/Properties/AssemblyInfo.cs \ - csharp/src/packages/repositories.config \ - csharp/src/ProtocolBuffers.Test/AbstractMessageTest.cs \ - csharp/src/ProtocolBuffers.Test/TestProtos/GoogleSize.cs \ - csharp/src/ProtocolBuffers.Test/TestProtos/GoogleSpeed.cs \ - csharp/src/ProtocolBuffers.Test/TestProtos/UnittestEnormousDescriptor.cs \ - csharp/src/ProtocolBuffers.Test/TestProtos/UnknownEnumTest.cs \ - csharp/src/ProtocolBuffers.Test/TestProtos/UnittestMset.cs \ - csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImport.cs \ - csharp/src/ProtocolBuffers.Test/TestProtos/UnittestCustomOptions.cs \ - csharp/src/ProtocolBuffers.Test/TestProtos/UnittestOptimizeFor.cs \ - csharp/src/ProtocolBuffers.Test/TestProtos/UnittestNoFieldPresence.cs \ - csharp/src/ProtocolBuffers.Test/TestProtos/Unittest.cs \ - csharp/src/ProtocolBuffers.Test/TestProtos/UnittestIssues.cs \ - csharp/src/ProtocolBuffers.Test/TestProtos/UnittestExtrasXmltest.cs \ - csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImportPublic.cs \ - csharp/src/ProtocolBuffers.Test/TestProtos/UnittestDropUnknownFields.cs \ - csharp/src/ProtocolBuffers.Test/CodedInputStreamTest.cs \ - csharp/src/ProtocolBuffers.Test/packages.config \ - csharp/src/ProtocolBuffers.Test/TestReaderForUrlEncoded.cs \ - csharp/src/ProtocolBuffers.Test/ByteStringTest.cs \ - csharp/src/ProtocolBuffers.Test/ReusableBuilderTest.cs \ - csharp/src/ProtocolBuffers.Test/TestUtil.cs \ - csharp/src/ProtocolBuffers.Test/TestResources.cs \ - csharp/src/ProtocolBuffers.Test/Collections/PopsicleListTest.cs \ - csharp/src/ProtocolBuffers.Test/ProtocolBuffers.Test.csproj \ - csharp/src/ProtocolBuffers.Test/IssuesTest.cs \ - csharp/src/ProtocolBuffers.Test/UnknownFieldSetTest.cs \ - csharp/src/ProtocolBuffers.Test/TestMimeMessageFormats.cs \ - csharp/src/ProtocolBuffers.Test/App.xaml.cs \ - csharp/src/ProtocolBuffers.Test/DeprecatedMemberTest.cs \ - csharp/src/ProtocolBuffers.Test/DynamicMessageTest.cs \ - csharp/src/ProtocolBuffers.Test/MessageStreamWriterTest.cs \ - csharp/src/ProtocolBuffers.Test/NameHelpersTest.cs \ - csharp/src/ProtocolBuffers.Test/GeneratedMessageTest.cs \ - csharp/src/ProtocolBuffers.Test/TestWriterFormatXml.cs \ - csharp/src/ProtocolBuffers.Test/ExtendableMessageTest.cs \ - csharp/src/ProtocolBuffers.Test/WireFormatTest.cs \ - csharp/src/ProtocolBuffers.Test/TestWriterFormatJson.cs \ - csharp/src/ProtocolBuffers.Test/MessageUtilTest.cs \ - csharp/src/ProtocolBuffers.Test/App.xaml \ - csharp/src/ProtocolBuffers.Test/Properties/AppManifest.xml \ - csharp/src/ProtocolBuffers.Test/Properties/AssemblyInfo.cs \ - csharp/src/ProtocolBuffers.Test/Properties/OutOfBrowserSettings.xml \ - csharp/src/ProtocolBuffers.Test/TextFormatTest.cs \ - csharp/src/ProtocolBuffers.Test/CodedOutputStreamTest.cs \ - csharp/src/ProtocolBuffers.Test/MessageTest.cs \ - csharp/src/ProtocolBuffers.Test/DescriptorsTest.cs \ - csharp/src/ProtocolBuffers.Test/Compatibility/DictionaryCompatibilityTests.cs \ - csharp/src/ProtocolBuffers.Test/Compatibility/JsonCompatibilityTests.cs \ - csharp/src/ProtocolBuffers.Test/Compatibility/TextCompatibilityTests.cs \ - csharp/src/ProtocolBuffers.Test/Compatibility/TestResources.cs \ - csharp/src/ProtocolBuffers.Test/Compatibility/google_message1.dat \ - csharp/src/ProtocolBuffers.Test/Compatibility/CompatibilityTests.cs \ - csharp/src/ProtocolBuffers.Test/Compatibility/google_message2.dat \ - csharp/src/ProtocolBuffers.Test/Compatibility/XmlCompatibilityTests.cs \ - csharp/src/ProtocolBuffers.Test/Compatibility/BinaryCompatibilityTests.cs \ - csharp/src/ProtocolBuffers.Test/GeneratedBuilderTest.cs \ - csharp/src/ProtocolBuffers.Test/ReflectionTester.cs \ - csharp/src/ProtocolBuffers.Test/FieldPresenceTest.cs \ - csharp/src/ProtocolBuffers.Test/TestCornerCases.cs \ - csharp/src/ProtocolBuffers.Test/MessageStreamIteratorTest.cs \ - csharp/buildall.sh \ - csharp/README.md \ - csharp/.gitignore \ - csharp/protos/extest/unittest_extras_lite.proto \ - csharp/protos/extest/unittest_extras_xmltest.proto \ - csharp/protos/extest/unittest_extras_full.proto \ - csharp/protos/extest/unittest_issues.proto \ - csharp/generate_protos.sh \ - csharp/CHANGES.txt \ - csharp/keys/generate_new_key.bat \ - csharp/keys/Google.ProtocolBuffers.snk \ - csharp/testdata/golden_message \ - csharp/testdata/text_format_unittest_data.txt \ - csharp/testdata/golden_packed_fields_message \ - csharp/testdata/text_format_unittest_extensions_data.txt \ - csharp/build/build.bat \ - csharp/build/googlecode_upload.py \ - csharp/build/build.csproj \ - csharp/build/Google.ProtocolBuffersLite.nuspec \ - csharp/build/Common.targets \ - csharp/build/Google.ProtocolBuffers.nuspec \ - csharp/build/target.csproj \ - csharp/build/nuspec.xsd \ - csharp/build/BuildAll.bat \ - csharp/build/RunBenchmarks.bat \ - csharp/build/publish.csproj +csharp_EXTRA_DIST= \ + csharp/CHANGES.txt \ + csharp/README.md \ + csharp/build_packages.bat \ + csharp/buildall.sh \ + csharp/generate_protos.sh \ + csharp/keys/Google.Protobuf.public.snk \ + csharp/keys/README.md \ + csharp/protos/unittest_issues.proto \ + csharp/src/AddressBook/AddPerson.cs \ + csharp/src/AddressBook/AddressBook.csproj \ + csharp/src/AddressBook/Addressbook.cs \ + csharp/src/AddressBook/ListPeople.cs \ + csharp/src/AddressBook/Program.cs \ + csharp/src/AddressBook/Properties/AssemblyInfo.cs \ + csharp/src/AddressBook/SampleUsage.cs \ + csharp/src/AddressBook/app.config \ + csharp/src/Google.Protobuf.JsonDump/Google.Protobuf.JsonDump.csproj \ + csharp/src/Google.Protobuf.JsonDump/Program.cs \ + csharp/src/Google.Protobuf.JsonDump/Properties/AssemblyInfo.cs \ + csharp/src/Google.Protobuf.JsonDump/app.config \ + csharp/src/Google.Protobuf.Test/ByteStringTest.cs \ + csharp/src/Google.Protobuf.Test/CodedInputStreamExtensions.cs \ + csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs \ + csharp/src/Google.Protobuf.Test/CodedOutputStreamTest.cs \ + csharp/src/Google.Protobuf.Test/Collections/MapFieldTest.cs \ + csharp/src/Google.Protobuf.Test/Collections/RepeatedFieldTest.cs \ + csharp/src/Google.Protobuf.Test/DeprecatedMemberTest.cs \ + csharp/src/Google.Protobuf.Test/EqualityTester.cs \ + csharp/src/Google.Protobuf.Test/FieldCodecTest.cs \ + csharp/src/Google.Protobuf.Test/GeneratedMessageTest.cs \ + csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj \ + csharp/src/Google.Protobuf.Test/IssuesTest.cs \ + csharp/src/Google.Protobuf.Test/JsonFormatterTest.cs \ + csharp/src/Google.Protobuf.Test/Properties/AppManifest.xml \ + csharp/src/Google.Protobuf.Test/Properties/AssemblyInfo.cs \ + csharp/src/Google.Protobuf.Test/Reflection/DescriptorsTest.cs \ + csharp/src/Google.Protobuf.Test/SampleEnum.cs \ + csharp/src/Google.Protobuf.Test/SampleMessages.cs \ + csharp/src/Google.Protobuf.Test/TestCornerCases.cs \ + csharp/src/Google.Protobuf.Test/TestProtos/MapUnittestProto3.cs \ + csharp/src/Google.Protobuf.Test/TestProtos/UnittestImportProto3.cs \ + csharp/src/Google.Protobuf.Test/TestProtos/UnittestImportPublicProto3.cs \ + csharp/src/Google.Protobuf.Test/TestProtos/UnittestIssues.cs \ + csharp/src/Google.Protobuf.Test/TestProtos/UnittestProto3.cs \ + csharp/src/Google.Protobuf.Test/TestProtos/UnittestWellKnownTypes.cs \ + csharp/src/Google.Protobuf.Test/WellKnownTypes/WrappersTest.cs \ + csharp/src/Google.Protobuf.Test/packages.config \ + csharp/src/Google.Protobuf.sln \ + csharp/src/Google.Protobuf/ByteArray.cs \ + csharp/src/Google.Protobuf/ByteString.cs \ + csharp/src/Google.Protobuf/CodedInputStream.cs \ + csharp/src/Google.Protobuf/CodedOutputStream.ComputeSize.cs \ + csharp/src/Google.Protobuf/CodedOutputStream.cs \ + csharp/src/Google.Protobuf/Collections/MapField.cs \ + csharp/src/Google.Protobuf/Collections/ReadOnlyDictionary.cs \ + csharp/src/Google.Protobuf/Collections/RepeatedField.cs \ + csharp/src/Google.Protobuf/FieldCodec.cs \ + csharp/src/Google.Protobuf/FrameworkPortability.cs \ + csharp/src/Google.Protobuf/Google.Protobuf.csproj \ + csharp/src/Google.Protobuf/Google.Protobuf.nuspec \ + csharp/src/Google.Protobuf/IMessage.cs \ + csharp/src/Google.Protobuf/InvalidProtocolBufferException.cs \ + csharp/src/Google.Protobuf/JsonFormatter.cs \ + csharp/src/Google.Protobuf/LimitedInputStream.cs \ + csharp/src/Google.Protobuf/MessageExtensions.cs \ + csharp/src/Google.Protobuf/MessageParser.cs \ + csharp/src/Google.Protobuf/Preconditions.cs \ + csharp/src/Google.Protobuf/Properties/AssemblyInfo.cs \ + csharp/src/Google.Protobuf/Reflection/DescriptorBase.cs \ + csharp/src/Google.Protobuf/Reflection/DescriptorPool.cs \ + csharp/src/Google.Protobuf/Reflection/DescriptorProtoFile.cs \ + csharp/src/Google.Protobuf/Reflection/DescriptorUtil.cs \ + csharp/src/Google.Protobuf/Reflection/DescriptorValidationException.cs \ + csharp/src/Google.Protobuf/Reflection/EnumDescriptor.cs \ + csharp/src/Google.Protobuf/Reflection/EnumValueDescriptor.cs \ + csharp/src/Google.Protobuf/Reflection/FieldAccessorBase.cs \ + csharp/src/Google.Protobuf/Reflection/FieldDescriptor.cs \ + csharp/src/Google.Protobuf/Reflection/FieldType.cs \ + csharp/src/Google.Protobuf/Reflection/FileDescriptor.cs \ + csharp/src/Google.Protobuf/Reflection/GeneratedCodeInfo.cs \ + csharp/src/Google.Protobuf/Reflection/IDescriptor.cs \ + csharp/src/Google.Protobuf/Reflection/IFieldAccessor.cs \ + csharp/src/Google.Protobuf/Reflection/MapFieldAccessor.cs \ + csharp/src/Google.Protobuf/Reflection/MessageDescriptor.cs \ + csharp/src/Google.Protobuf/Reflection/MethodDescriptor.cs \ + csharp/src/Google.Protobuf/Reflection/OneofAccessor.cs \ + csharp/src/Google.Protobuf/Reflection/OneofDescriptor.cs \ + csharp/src/Google.Protobuf/Reflection/PackageDescriptor.cs \ + csharp/src/Google.Protobuf/Reflection/PartialClasses.cs \ + csharp/src/Google.Protobuf/Reflection/ReflectionUtil.cs \ + csharp/src/Google.Protobuf/Reflection/RepeatedFieldAccessor.cs \ + csharp/src/Google.Protobuf/Reflection/ServiceDescriptor.cs \ + csharp/src/Google.Protobuf/Reflection/SingleFieldAccessor.cs \ + csharp/src/Google.Protobuf/WellKnownTypes/Any.cs \ + csharp/src/Google.Protobuf/WellKnownTypes/Api.cs \ + csharp/src/Google.Protobuf/WellKnownTypes/Duration.cs \ + csharp/src/Google.Protobuf/WellKnownTypes/Empty.cs \ + csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs \ + csharp/src/Google.Protobuf/WellKnownTypes/SourceContext.cs \ + csharp/src/Google.Protobuf/WellKnownTypes/Struct.cs \ + csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs \ + csharp/src/Google.Protobuf/WellKnownTypes/Type.cs \ + csharp/src/Google.Protobuf/WellKnownTypes/Wrappers.cs \ + csharp/src/Google.Protobuf/WireFormat.cs \ + csharp/src/packages/repositories.config java_EXTRA_DIST= \ java/src/main/java/com/google/protobuf/AbstractMessage.java \ diff --git a/Protobuf.podspec b/Protobuf.podspec index 6aa89902c2879..0cd52025d23e2 100644 --- a/Protobuf.podspec +++ b/Protobuf.podspec @@ -18,7 +18,7 @@ Pod::Spec.new do |s| 'objectivec/google/protobuf/*.pbobjc.{h,m}' s.header_mappings_dir = 'objectivec' - s.ios.deployment_target = '6.0' - s.osx.deployment_target = '10.8' + s.ios.deployment_target = '7.1' + s.osx.deployment_target = '10.9' s.requires_arc = false end diff --git a/appveyor.bat b/appveyor.bat new file mode 100644 index 0000000000000..356a13f86bf5b --- /dev/null +++ b/appveyor.bat @@ -0,0 +1,29 @@ +setlocal + +IF %language%==cpp GOTO build_cpp +IF %language%==csharp GOTO build_csharp + +echo Unsupported language %language%. Exiting. +goto :error + +:build_cpp +echo Building C++ +mkdir build_msvc +cd build_msvc +cmake -G "%generator%" -DBUILD_SHARED_LIBS=%BUILD_DLL% ../cmake +msbuild protobuf.sln /p:Platform=%vcplatform% /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" || goto error +cd %configuration% +tests.exe || goto error +goto :EOF + +:build_csharp +echo Building C# +cd csharp\src +nuget restore +msbuild Google.Protobuf.sln /p:Platform="Any CPU" /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" || goto error +nunit-console Google.Protobuf.Test\bin\%configuration%\Google.Protobuf.Test.dll || goto error +goto :EOF + +:error +echo Failed! +EXIT /b %ERRORLEVEL% \ No newline at end of file diff --git a/appveyor.yml b/appveyor.yml index d49086544d0bd..3447602e31ed1 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,34 +1,32 @@ -# Only test one combination: "Visual Studio 12 + Win64 + Debug + DLL". We can -# test more combinations but AppVeyor just takes too long to finish (each -# combination takes ~15mins). -platform: - - Win64 - -configuration: - - Debug - -environment: - matrix: - - BUILD_DLL: ON - -install: - - ps: Start-FileDownload https://googlemock.googlecode.com/files/gmock-1.7.0.zip - - 7z x gmock-1.7.0.zip - - rename gmock-1.7.0 gmock - -before_build: - - if %platform%==Win32 set generator=Visual Studio 12 - - if %platform%==Win64 set generator=Visual Studio 12 Win64 - - if %platform%==Win32 set vcplatform=Win32 - - if %platform%==Win64 set vcplatform=x64 - -build_script: - - mkdir build_msvc - - cd build_msvc - - cmake -G "%generator%" -DBUILD_SHARED_LIBS=%BUILD_DLL% ../cmake - - msbuild protobuf.sln /p:Platform=%vcplatform% /logger:"C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll" - - cd %configuration% - - tests.exe - -skip_commits: - message: /.*\[skip appveyor\].*/ +# Only test one combination: "Visual Studio 12 + Win64 + Debug + DLL". We can +# test more combinations but AppVeyor just takes too long to finish (each +# combination takes ~15mins). +platform: + - Win64 + +configuration: + - Debug + +environment: + matrix: + - language: cpp + BUILD_DLL: ON + + - language: csharp + +install: + - ps: Start-FileDownload https://googlemock.googlecode.com/files/gmock-1.7.0.zip + - 7z x gmock-1.7.0.zip + - rename gmock-1.7.0 gmock + +before_build: + - if %platform%==Win32 set generator=Visual Studio 12 + - if %platform%==Win64 set generator=Visual Studio 12 Win64 + - if %platform%==Win32 set vcplatform=Win32 + - if %platform%==Win64 set vcplatform=x64 + +build_script: + - CALL appveyor.bat + +skip_commits: + message: /.*\[skip appveyor\].*/ diff --git a/benchmarks/google_size.proto b/benchmarks/google_size.proto index e0fcb2e096062..d2d319f31c100 100644 --- a/benchmarks/google_size.proto +++ b/benchmarks/google_size.proto @@ -4,7 +4,6 @@ package benchmarks; option java_outer_classname = "GoogleSize"; option optimize_for = CODE_SIZE; -option csharp_namespace = "Google.ProtocolBuffers.TestProtos"; message SizeMessage1 { required string field1 = 1; diff --git a/benchmarks/google_speed.proto b/benchmarks/google_speed.proto index 3bc5fd2dadd15..16f6d678041e1 100644 --- a/benchmarks/google_speed.proto +++ b/benchmarks/google_speed.proto @@ -4,7 +4,6 @@ package benchmarks; option java_outer_classname = "GoogleSpeed"; option optimize_for = SPEED; -option csharp_namespace = "Google.ProtocolBuffers.TestProtos"; message SpeedMessage1 { required string field1 = 1; diff --git a/cmake/CMakeLists.txt b/cmake/CMakeLists.txt index d36292df689c9..33e069fe6ab23 100644 --- a/cmake/CMakeLists.txt +++ b/cmake/CMakeLists.txt @@ -1,13 +1,42 @@ +# Minimum CMake required cmake_minimum_required(VERSION 2.8) +# Project project(protobuf C CXX) +# Options option(BUILD_TESTING "Build tests" ON) option(BUILD_SHARED_LIBS "Build Shared Libraries" OFF) if (MSVC) option(ZLIB "Build with zlib support" OFF) endif (MSVC) +# Path to main configure script +set(protobuf_CONFIGURE_SCRIPT "../configure.ac") + +# Parse version from configure script +file(STRINGS "${protobuf_CONFIGURE_SCRIPT}" protobuf_VERSION_LINE + LIMIT_COUNT 1 + REGEX "^AC_INIT") +# Replace special characters +string(REPLACE "(" "_" protobuf_VERSION_LINE ${protobuf_VERSION_LINE}) +string(REPLACE ")" "_" protobuf_VERSION_LINE ${protobuf_VERSION_LINE}) +string(REPLACE "[" "_" protobuf_VERSION_LINE ${protobuf_VERSION_LINE}) +string(REPLACE "]" "_" protobuf_VERSION_LINE ${protobuf_VERSION_LINE}) +# Parse version string +string(REGEX REPLACE "^AC_INIT__Protocol Buffers_,_([^_]+).*$" "\\1" + protobuf_VERSION_STRING "${protobuf_VERSION_LINE}") +# Parse version tweaks +string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+).*$" "\\1" + protobuf_VERSION_MAJOR "${protobuf_VERSION_STRING}") +string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+).*$" "\\2" + protobuf_VERSION_MINOR "${protobuf_VERSION_STRING}") +string(REGEX REPLACE "^([0-9]+)\\.([0-9]+)\\.([0-9]+).*$" "\\3" + protobuf_VERSION_PATCH "${protobuf_VERSION_STRING}") +# Package version +set(protobuf_VERSION + "${protobuf_VERSION_MAJOR}.${protobuf_VERSION_MINOR}.${protobuf_VERSION_PATCH}") + add_definitions(-DGOOGLE_PROTOBUF_CMAKE_BUILD) find_package(Threads REQUIRED) @@ -43,6 +72,19 @@ endif (HAVE_ZLIB) if (MSVC) if (BUILD_SHARED_LIBS) add_definitions(-DPROTOBUF_USE_DLLS) + else (BUILD_SHARED_LIBS) + # In case we are building static libraries, link also the runtime library statically + # so that MSVCR*.DLL is not required at runtime. + # https://msdn.microsoft.com/en-us/library/2kzt1wy3.aspx + # This is achieved by replacing msvc option /MD with /MT and /MDd with /MTd + # http://www.cmake.org/Wiki/CMake_FAQ#How_can_I_build_my_MSVC_application_with_a_static_runtime.3F + foreach(flag_var + CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE + CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO) + if(${flag_var} MATCHES "/MD") + string(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}") + endif(${flag_var} MATCHES "/MD") + endforeach(flag_var) endif (BUILD_SHARED_LIBS) add_definitions(/wd4244 /wd4267 /wd4018 /wd4355 /wd4800 /wd4251 /wd4996 /wd4146 /wd4305) endif (MSVC) @@ -73,6 +115,9 @@ include(libprotobuf-lite.cmake) include(libprotobuf.cmake) include(libprotoc.cmake) include(protoc.cmake) + if (BUILD_TESTING) include(tests.cmake) endif (BUILD_TESTING) + +include(install.cmake) diff --git a/cmake/extract_includes.bat.in b/cmake/extract_includes.bat.in index 25c60b17f1435..eaf9758317699 100644 --- a/cmake/extract_includes.bat.in +++ b/cmake/extract_includes.bat.in @@ -21,6 +21,7 @@ copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\code_generato copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\command_line_interface.h include\google\protobuf\compiler\command_line_interface.h copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\cpp\cpp_generator.h include\google\protobuf\compiler\cpp\cpp_generator.h copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\csharp\csharp_generator.h include\google\protobuf\compiler\csharp\csharp_generator.h +copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\csharp\csharp_names.h include\google\protobuf\compiler\csharp\csharp_names.h copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\importer.h include\google\protobuf\compiler\importer.h copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\java\java_generator.h include\google\protobuf\compiler\java\java_generator.h copy ${PROTOBUF_SOURCE_WIN32_PATH}\..\src\google\protobuf\compiler\java\java_names.h include\google\protobuf\compiler\java\java_names.h diff --git a/cmake/install.cmake b/cmake/install.cmake new file mode 100644 index 0000000000000..e14ef1d27fb1b --- /dev/null +++ b/cmake/install.cmake @@ -0,0 +1,103 @@ +include(GNUInstallDirs) + +foreach(_library + libprotobuf-lite + libprotobuf + libprotoc) + set_property(TARGET ${_library} + PROPERTY INTERFACE_INCLUDE_DIRECTORIES + $) + install(TARGETS ${_library} EXPORT protobuf-targets + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT ${_library} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT ${_library} + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT ${_library}) +endforeach() + +install(TARGETS protoc EXPORT protobuf-targets + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT protoc) + +if(TRUE) + file(STRINGS extract_includes.bat.in _extract_strings + REGEX "^copy") + foreach(_extract_string ${_extract_strings}) + string(REPLACE "copy \${PROTOBUF_SOURCE_WIN32_PATH}\\" "" + _extract_string ${_extract_string}) + string(REPLACE "\\" "/" _extract_string ${_extract_string}) + string(REGEX MATCH "^[^ ]+" + _extract_from ${_extract_string}) + string(REGEX REPLACE "^${_extract_from} ([^$]+)" "\\1" + _extract_to ${_extract_string}) + get_filename_component(_extract_from "${protobuf_SOURCE_DIR}/${_extract_from}" ABSOLUTE) + get_filename_component(_extract_name ${_extract_to} NAME) + get_filename_component(_extract_to ${_extract_to} PATH) + string(REPLACE "include/" "${CMAKE_INSTALL_INCLUDEDIR}/" + _extract_to "${_extract_to}") + if(EXISTS "${_extract_from}") + install(FILES "${_extract_from}" + DESTINATION "${_extract_to}" + COMPONENT protobuf-headers + RENAME "${_extract_name}") + else() + message(AUTHOR_WARNING "The file \"${_extract_from}\" is listed in " + "\"${protobuf_SOURCE_DIR}/cmake/extract_includes.bat.in\" " + "but there not exists. The file will not be installed.") + endif() + endforeach() +endif() + +# Internal function for parsing auto tools scripts +function(_protobuf_auto_list FILE_NAME VARIABLE) + file(STRINGS ${FILE_NAME} _strings) + set(_list) + foreach(_string ${_strings}) + set(_found) + string(REGEX MATCH "^[ \t]*${VARIABLE}[ \t]*=[ \t]*" _found "${_string}") + if(_found) + string(LENGTH "${_found}" _length) + string(SUBSTRING "${_string}" ${_length} -1 _draft_list) + foreach(_item ${_draft_list}) + string(STRIP "${_item}" _item) + list(APPEND _list "${_item}") + endforeach() + endif() + endforeach() + set(${VARIABLE} ${_list} PARENT_SCOPE) +endfunction() + +# Install well-known type proto files +_protobuf_auto_list("../src/Makefile.am" nobase_dist_proto_DATA) +foreach(_file ${nobase_dist_proto_DATA}) + get_filename_component(_file_from "../src/${_file}" ABSOLUTE) + get_filename_component(_file_name ${_file} NAME) + get_filename_component(_file_path ${_file} PATH) + if(EXISTS "${_file_from}") + install(FILES "${_file_from}" + DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${_file_path}" + COMPONENT protobuf-protos + RENAME "${_file_name}") + else() + message(AUTHOR_WARNING "The file \"${_file_from}\" is listed in " + "\"${protobuf_SOURCE_DIR}/../src/Makefile.am\" as nobase_dist_proto_DATA " + "but there not exists. The file will not be installed.") + endif() +endforeach() + +# Export configuration + +install(EXPORT protobuf-targets + DESTINATION "lib/cmake/protobuf" + COMPONENT protobuf-export) + +configure_file(protobuf-config.cmake.in + protobuf-config.cmake @ONLY) +configure_file(protobuf-config-version.cmake.in + protobuf-config-version.cmake @ONLY) +configure_file(protobuf-module.cmake.in + protobuf-module.cmake @ONLY) + +install(FILES + "${protobuf_BINARY_DIR}/protobuf-config.cmake" + "${protobuf_BINARY_DIR}/protobuf-config-version.cmake" + "${protobuf_BINARY_DIR}/protobuf-module.cmake" + DESTINATION "lib/cmake/protobuf" + COMPONENT protobuf-export) diff --git a/cmake/libprotobuf-lite.cmake b/cmake/libprotobuf-lite.cmake index 9b14d4ccef581..e2cec9d1145b7 100644 --- a/cmake/libprotobuf-lite.cmake +++ b/cmake/libprotobuf-lite.cmake @@ -25,6 +25,7 @@ set(libprotobuf_lite_files add_library(libprotobuf-lite ${libprotobuf_lite_files}) target_link_libraries(libprotobuf-lite ${CMAKE_THREAD_LIBS_INIT}) +target_include_directories(libprotobuf-lite PUBLIC ${protobuf_source_dir}/src) set_target_properties(libprotobuf-lite PROPERTIES COMPILE_DEFINITIONS LIBPROTOBUF_EXPORTS OUTPUT_NAME ${LIB_PREFIX}protobuf-lite) diff --git a/cmake/libprotobuf.cmake b/cmake/libprotobuf.cmake index 49a12f7d211e4..f25e8c08a9ca9 100644 --- a/cmake/libprotobuf.cmake +++ b/cmake/libprotobuf.cmake @@ -56,6 +56,7 @@ set(libprotobuf_files add_library(libprotobuf ${libprotobuf_lite_files} ${libprotobuf_files}) target_link_libraries(libprotobuf ${CMAKE_THREAD_LIBS_INIT} ${ZLIB_LIBRARIES}) +target_include_directories(libprotobuf PUBLIC ${protobuf_source_dir}/src) set_target_properties(libprotobuf PROPERTIES COMPILE_DEFINITIONS LIBPROTOBUF_EXPORTS OUTPUT_NAME ${LIB_PREFIX}protobuf) diff --git a/cmake/libprotoc.cmake b/cmake/libprotoc.cmake index aaed4863382bb..7aa92ee19210c 100644 --- a/cmake/libprotoc.cmake +++ b/cmake/libprotoc.cmake @@ -16,10 +16,10 @@ set(libprotoc_files ${protobuf_source_dir}/src/google/protobuf/compiler/cpp/cpp_string_field.cc ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_enum.cc ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_enum_field.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_extension.cc ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_field_base.cc ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_generator.cc ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_helpers.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_map_field.cc ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_message.cc ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_message_field.cc ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc @@ -28,7 +28,7 @@ set(libprotoc_files ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_source_generator_base.cc ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_umbrella_class.cc - ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_writer.cc + ${protobuf_source_dir}/src/google/protobuf/compiler/csharp/csharp_wrapper_field.cc ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_context.cc ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_doc_comment.cc ${protobuf_source_dir}/src/google/protobuf/compiler/java/java_enum.cc diff --git a/cmake/protobuf-config-version.cmake.in b/cmake/protobuf-config-version.cmake.in new file mode 100644 index 0000000000000..07ab40b990ea6 --- /dev/null +++ b/cmake/protobuf-config-version.cmake.in @@ -0,0 +1 @@ +set(PACKAGE_VERSION @protobuf_VERSION@) diff --git a/cmake/protobuf-config.cmake.in b/cmake/protobuf-config.cmake.in new file mode 100644 index 0000000000000..51d715cfa4c2d --- /dev/null +++ b/cmake/protobuf-config.cmake.in @@ -0,0 +1,27 @@ +# Version info variables +set(PROTOBUF_VERSION "@protobuf_VERSION@") +set(PROTOBUF_VERSION_STRING "@protobuf_VERSION_STRING@") + +# Current dir +get_filename_component(_PROTOBUF_PACKAGE_PREFIX + "${CMAKE_CURRENT_LIST_FILE}" PATH) + +# Imported targets +include("${_PROTOBUF_PACKAGE_PREFIX}/protobuf-targets.cmake") + +# Compute the installation prefix relative to this file. +get_filename_component(_PROTOBUF_IMPORT_PREFIX + "${_PROTOBUF_PACKAGE_PREFIX}" PATH) +get_filename_component(_PROTOBUF_IMPORT_PREFIX + "${_PROTOBUF_IMPORT_PREFIX}" PATH) +get_filename_component(_PROTOBUF_IMPORT_PREFIX + "${_PROTOBUF_IMPORT_PREFIX}" PATH) + +# CMake FindProtobuf module compatible file +if(NOT DEFINED PROTOBUF_MODULE_COMPATIBLE OR "${PROTOBUF_MODULE_COMPATIBLE}") + include("${_PROTOBUF_PACKAGE_PREFIX}/protobuf-module.cmake") +endif() + +# Cleanup temporary variables. +set(_PROTOBUF_PACKAGE_PREFIX) +set(_PROTOBUF_IMPORT_PREFIX) diff --git a/cmake/protobuf-module.cmake.in b/cmake/protobuf-module.cmake.in new file mode 100644 index 0000000000000..d81dc459b6a54 --- /dev/null +++ b/cmake/protobuf-module.cmake.in @@ -0,0 +1,139 @@ +if(PROTOBUF_SRC_ROOT_FOLDER) + message(AUTHOR_WARNING "Variable PROTOBUF_SRC_ROOT_FOLDER defined, but not" + " used in CONFIG mode") +endif() + +function(PROTOBUF_GENERATE_CPP SRCS HDRS) + if(NOT ARGN) + message(SEND_ERROR "Error: PROTOBUF_GENERATE_CPP() called without any proto files") + return() + endif() + + if(PROTOBUF_GENERATE_CPP_APPEND_PATH) + # Create an include path for each file specified + foreach(FIL ${ARGN}) + get_filename_component(ABS_FIL ${FIL} ABSOLUTE) + get_filename_component(ABS_PATH ${ABS_FIL} PATH) + list(FIND _protobuf_include_path ${ABS_PATH} _contains_already) + if(${_contains_already} EQUAL -1) + list(APPEND _protobuf_include_path -I ${ABS_PATH}) + endif() + endforeach() + else() + set(_protobuf_include_path -I ${CMAKE_CURRENT_SOURCE_DIR}) + endif() + + # Add well-known type protos include path + list(APPEND _protobuf_include_path + -I "${_PROTOBUF_IMPORT_PREFIX}/@CMAKE_INSTALL_INCLUDEDIR@") + + if(DEFINED PROTOBUF_IMPORT_DIRS) + foreach(DIR ${PROTOBUF_IMPORT_DIRS}) + get_filename_component(ABS_PATH ${DIR} ABSOLUTE) + list(FIND _protobuf_include_path ${ABS_PATH} _contains_already) + if(${_contains_already} EQUAL -1) + list(APPEND _protobuf_include_path -I ${ABS_PATH}) + endif() + endforeach() + endif() + + set(${SRCS}) + set(${HDRS}) + foreach(FIL ${ARGN}) + get_filename_component(ABS_FIL ${FIL} ABSOLUTE) + get_filename_component(FIL_WE ${FIL} NAME_WE) + + list(APPEND ${SRCS} "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb.cc") + list(APPEND ${HDRS} "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb.h") + + add_custom_command( + OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb.cc" + "${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.pb.h" + COMMAND ${PROTOBUF_PROTOC_EXECUTABLE} + ARGS --cpp_out ${CMAKE_CURRENT_BINARY_DIR} ${_protobuf_include_path} ${ABS_FIL} + DEPENDS ${ABS_FIL} ${PROTOBUF_PROTOC_EXECUTABLE} + COMMENT "Running C++ protocol buffer compiler on ${FIL}" + VERBATIM) + endforeach() + + set_source_files_properties(${${SRCS}} ${${HDRS}} PROPERTIES GENERATED TRUE) + set(${SRCS} ${${SRCS}} PARENT_SCOPE) + set(${HDRS} ${${HDRS}} PARENT_SCOPE) +endfunction() + +# Internal function: search for normal library as well as a debug one +# if the debug one is specified also include debug/optimized keywords +# in *_LIBRARIES variable +function(_protobuf_find_libraries name filename) + get_target_property(${name}_LIBRARY lib${filename} + IMPORTED_LOCATION_RELEASE) + set(${name}_LIBRARY "${${name}_LIBRARY}" PARENT_SCOPE) + get_target_property(${name}_LIBRARY_DEBUG lib${filename} + IMPORTED_LOCATION_DEBUG) + set(${name}_LIBRARY_DEBUG "${${name}_LIBRARY_DEBUG}" PARENT_SCOPE) + + if(NOT ${name}_LIBRARY_DEBUG) + # There is no debug library + set(${name}_LIBRARY_DEBUG ${${name}_LIBRARY} PARENT_SCOPE) + set(${name}_LIBRARIES ${${name}_LIBRARY} PARENT_SCOPE) + else() + # There IS a debug library + set(${name}_LIBRARIES + optimized ${${name}_LIBRARY} + debug ${${name}_LIBRARY_DEBUG} + PARENT_SCOPE + ) + endif() +endfunction() + +# Internal function: find threads library +function(_protobuf_find_threads) + set(CMAKE_THREAD_PREFER_PTHREAD TRUE) + find_package(Threads) + if(Threads_FOUND) + list(APPEND PROTOBUF_LIBRARIES ${CMAKE_THREAD_LIBS_INIT}) + set(PROTOBUF_LIBRARIES "${PROTOBUF_LIBRARIES}" PARENT_SCOPE) + endif() +endfunction() + +# +# Main. +# + +# By default have PROTOBUF_GENERATE_CPP macro pass -I to protoc +# for each directory where a proto file is referenced. +if(NOT DEFINED PROTOBUF_GENERATE_CPP_APPEND_PATH) + set(PROTOBUF_GENERATE_CPP_APPEND_PATH TRUE) +endif() + +# The Protobuf library +_protobuf_find_libraries(PROTOBUF protobuf) + +# The Protobuf Lite library +_protobuf_find_libraries(PROTOBUF_LITE protobuf-lite) + +# The Protobuf Protoc Library +_protobuf_find_libraries(PROTOBUF_PROTOC protoc) + +if(UNIX) + _protobuf_find_threads() +endif() + +# Set the include directory +set(PROTOBUF_INCLUDE_DIR "${_PROTOBUF_IMPORT_PREFIX}/@CMAKE_INSTALL_INCLUDEDIR@") + +# Set the protoc Executable +get_target_property(PROTOBUF_PROTOC_EXECUTABLE protoc + IMPORTED_LOCATION_RELEASE) +if(NOT PROTOBUF_PROTOC_EXECUTABLE) + get_target_property(PROTOBUF_PROTOC_EXECUTABLE protoc + IMPORTED_LOCATION_DEBUG) +endif() + +include(FindPackageHandleStandardArgs) +FIND_PACKAGE_HANDLE_STANDARD_ARGS(PROTOBUF DEFAULT_MSG + PROTOBUF_LIBRARY PROTOBUF_INCLUDE_DIR) + +if(PROTOBUF_FOUND) + set(PROTOBUF_INCLUDE_DIRS ${PROTOBUF_INCLUDE_DIR}) +endif() diff --git a/conformance/Makefile.am b/conformance/Makefile.am index 972517151bcf2..c74eb1c8c3480 100644 --- a/conformance/Makefile.am +++ b/conformance/Makefile.am @@ -40,7 +40,7 @@ $(protoc_outputs): protoc_middleman BUILT_SOURCES = $(protoc_outputs) -CLEANFILES = $(protoc_outputs) protoc_middleman javac_middleman conformance-java +CLEANFILES = $(protoc_outputs) protoc_middleman javac_middleman conformance-java conformance-csharp MAINTAINERCLEANFILES = \ Makefile.in @@ -55,6 +55,15 @@ conformance-java: javac_middleman @echo 'java -classpath .:../java/target/classes ConformanceJava "$$@"' >> conformance-java @chmod +x conformance-java +# Currently the conformance code is alongside the rest of the C# +# source, as it's easier to maintain there. We assume we've already +# built that, so we just need a script to run it. +conformance-csharp: + @echo "Writing shortcut script conformance-csharp..." + @echo '#! /bin/sh' > conformance-csharp + @echo 'mono ../csharp/src/Google.Protobuf.Conformance/bin/Release/Google.Protobuf.Conformance.exe "$$@"' >> conformance-csharp + @chmod +x conformance-csharp + # Targets for actually running tests. test_cpp: protoc_middleman conformance-test-runner conformance-cpp ./conformance-test-runner --failure_list failure_list_cpp.txt ./conformance-cpp @@ -62,5 +71,8 @@ test_cpp: protoc_middleman conformance-test-runner conformance-cpp test_java: protoc_middleman conformance-test-runner conformance-java ./conformance-test-runner ./conformance-java +test_csharp: protoc_middleman conformance-test-runner conformance-csharp + ./conformance-test-runner --failure_list failure_list_csharp.txt ./conformance-csharp + test_ruby: protoc_middleman conformance-test-runner RUBYLIB=../ruby/lib:. ./conformance-test-runner --failure_list failure_list_ruby.txt ./conformance_ruby.rb diff --git a/conformance/failure_list_csharp.txt b/conformance/failure_list_csharp.txt new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/conformance/failure_list_ruby.txt b/conformance/failure_list_ruby.txt index 35d1ff9100e4d..ff220cb9902a5 100644 --- a/conformance/failure_list_ruby.txt +++ b/conformance/failure_list_ruby.txt @@ -1,17 +1,2 @@ JsonInput.HelloWorld.JsonOutput JsonInput.HelloWorld.ProtobufOutput -ProtobufInput.PrematureEofBeforeUnknownValue.DOUBLE -ProtobufInput.PrematureEofBeforeUnknownValue.FIXED32 -ProtobufInput.PrematureEofBeforeUnknownValue.FIXED64 -ProtobufInput.PrematureEofBeforeUnknownValue.FLOAT -ProtobufInput.PrematureEofBeforeUnknownValue.SFIXED32 -ProtobufInput.PrematureEofBeforeUnknownValue.SFIXED64 -ProtobufInput.PrematureEofInDelimitedDataForUnknownValue.BYTES -ProtobufInput.PrematureEofInDelimitedDataForUnknownValue.MESSAGE -ProtobufInput.PrematureEofInDelimitedDataForUnknownValue.STRING -ProtobufInput.PrematureEofInsideUnknownValue.DOUBLE -ProtobufInput.PrematureEofInsideUnknownValue.FIXED32 -ProtobufInput.PrematureEofInsideUnknownValue.FIXED64 -ProtobufInput.PrematureEofInsideUnknownValue.FLOAT -ProtobufInput.PrematureEofInsideUnknownValue.SFIXED32 -ProtobufInput.PrematureEofInsideUnknownValue.SFIXED64 diff --git a/csharp/.gitignore b/csharp/.gitignore index d7dcef598c7c5..07ea90ac404ba 100644 --- a/csharp/.gitignore +++ b/csharp/.gitignore @@ -3,25 +3,14 @@ # src/AddressBook/bin src/AddressBook/obj -src/ProtocolBuffers/bin/ -src/ProtocolBuffers/obj/ -src/ProtocolBuffers/objCF -src/ProtocolBuffers.Serialization/bin/ -src/ProtocolBuffers.Serialization/obj/ -src/ProtocolBuffers.Test/bin/ -src/ProtocolBuffers.Test/obj/ -src/ProtocolBuffersLite.Test/bin/ -src/ProtocolBuffersLite.Test/obj/ -src/ProtoBench/bin/ -src/ProtoBench/obj/ -src/ProtoDump/bin/ -src/ProtoDump/obj/ -src/ProtoGen/bin/ -src/ProtoGen/obj/ -src/ProtoGen.Test/bin/ -src/ProtoGen.Test/obj/ -src/ProtoMunge/bin/ -src/ProtoMunge/obj/ +src/Google.Protobuf/bin/ +src/Google.Protobuf/obj/ +src/Google.Protobuf.Conformance/bin/ +src/Google.Protobuf.Conformance/obj/ +src/Google.Protobuf.Test/bin/ +src/Google.Protobuf.Test/obj/ +src/Google.Protobuf.JsonDump/bin/ +src/Google.Protobuf.JsonDump/obj/ mono/bin mono/tmp mono/protoc @@ -36,6 +25,7 @@ lib/NUnit # *.user *.suo +*.nupkg _ReSharper.* *.sln.cache mono/TestResult.xml diff --git a/csharp/README.md b/csharp/README.md index d694828010b18..a798ee62c97f4 100644 --- a/csharp/README.md +++ b/csharp/README.md @@ -1,33 +1,45 @@ - This directory contains the C# Protocol Buffers runtime library. +Warning: experimental! +====================== + +This code is still under significant churn. Unlike the original port, +it only supports proto3 (but not *all* of proto3 yet) - there are no +unknown fields or extensions, for example. protoc will (eventually) +deliberately fail if it is asked to generate C# code for proto2 +messages other than descriptor.proto, which is still required for +reflection. (It's currently exposed publicly, but won't be +eventually.) + +Also unlike the original port, the new version embraces mutability - +there are no builder types. We plan to add "freezing" operations as +well as cloning, however. + Usage ===== -The easiest way to use C# protocol buffers in your project is to use the [Google.ProtocolBuffers NuGet package](http://www.nuget.org/packages/Google.ProtocolBuffers/). This package is the legacy package for C# protocol buffers, but it will work fine with C# code generated by `protoc` if you use proto2 syntax (The API of the runtime library haven't changed so far). +Use `protoc` with the `--csharp_out` option to generate C# files in the specified directory. +Include these in your C# project, and add a reference to the `Google.Protobuf` project. Currently +there is no NuGet package for this, but we will be building one as soon as the API is stable. + +Supported platforms +=================== -*WARNING: If you specify `syntax = "proto3";` in your .proto files, the generated code won't necessarily work with the legacy NuGet package. So before we officially add proto3 support, always use `syntax = "proto2";` (the default) in your protos.* +The runtime library is built as a portable class library, supporting: -We will definitely release a new NuGet package for the runtime library in the future. The new runtime library WILL contain significant semantic, backwardly-incompatible changes in proto handling (mostly because we will be adding proto3 support and we will be using that oportunity to make some design changes). So keep in mind that you will need to regenerate your proto files and switch to a new NuGet package once the new version of runtime library becomes available. +- .NET 4.5 +- Windows 8 +- Windows Phone Silverlight 8 +- Windows Phone 8.1 +- .NET Core (dnxcore) Building ======== -Open the `src/ProtocolBuffers.sln` solution in Visual Studio. Click "Build solution" to build the solution. You should be able to run the NUnit test from Test Explorer (you might need to install NUnit Visual Studio add-in). +Open the `src/Google.Protobuf.sln` solution in Visual Studio. Click "Build solution" to build the solution. You should be able to run the NUnit test from Test Explorer (you might need to install NUnit Visual Studio add-in). Supported Visual Studio versions are VS2013 (update 4) and VS2015. On Linux, you can also use Monodevelop 5.9 (older versions might work fine). -Proto2 & Proto3 -=============== - -*WARNING: Only proto2 is supported for now, proto3 is under construction.* - -C# protocol buffers are currently under development and you should expect semantic, backward-incompatible changes in the future. - -Also, as of now, only proto2 is supported. Proto3 support for C# is currently in progress -(both design & implementation) and you should not expect any of the proto3 features to work. -In fact, always use `syntax = "proto2";` in your .proto files for now, unless you are feeling like experimenting. - History of C# protobufs ======================= diff --git a/csharp/build/BuildAll.bat b/csharp/build/BuildAll.bat deleted file mode 100644 index 9bee73c7cf321..0000000000000 --- a/csharp/build/BuildAll.bat +++ /dev/null @@ -1,8 +0,0 @@ -@echo off -SET BUILD_TARGET=%~1 -SET BUILD_CONFIG=%~2 - -IF "%BUILD_TARGET%"=="" SET BUILD_TARGET=Rebuild -IF "%BUILD_CONFIG%"=="" SET BUILD_CONFIG=Debug - -CMD.exe /Q /C "CD %~dp0 && %WINDIR%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe /nologo build.csproj /t:%BUILD_TARGET% /toolsversion:4.0 "/p:Configuration=%BUILD_CONFIG%" %3 %4 %5 %6 diff --git a/csharp/build/Common.targets b/csharp/build/Common.targets deleted file mode 100644 index 2aa74dfed2f09..0000000000000 --- a/csharp/build/Common.targets +++ /dev/null @@ -1,122 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/csharp/build/Google.ProtocolBuffers.nuspec b/csharp/build/Google.ProtocolBuffers.nuspec deleted file mode 100644 index c355cd4abee01..0000000000000 --- a/csharp/build/Google.ProtocolBuffers.nuspec +++ /dev/null @@ -1,59 +0,0 @@ - - - - Google.ProtocolBuffers - $version$ - Jon Skeet - Jon Skeet - http://code.google.com/p/protobuf-csharp-port/source/browse/license.txt - http://code.google.com/p/protobuf-csharp-port/ - false - Copyright 2008 Google Inc. All rights reserved. - Protocol Buffers Binary Serialization Format Google - - Google.ProtocolBuffers - A managed code generator and library for Google's data interchange format. - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/csharp/build/Google.ProtocolBuffersLite.nuspec b/csharp/build/Google.ProtocolBuffersLite.nuspec deleted file mode 100644 index 8b9107f5a5c39..0000000000000 --- a/csharp/build/Google.ProtocolBuffersLite.nuspec +++ /dev/null @@ -1,60 +0,0 @@ - - - - Google.ProtocolBuffersLite - $version$ - Jon Skeet - Jon Skeet - http://code.google.com/p/protobuf-csharp-port/source/browse/license.txt - http://code.google.com/p/protobuf-csharp-port/ - false - Copyright 2008 Google Inc. All rights reserved. - Protocol Buffers Binary Serialization Format Google - - Google.ProtocolBuffersLite - A managed code generator and library for Google's data interchange format. - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/csharp/build/RunBenchmarks.bat b/csharp/build/RunBenchmarks.bat deleted file mode 100644 index d0e65010c5714..0000000000000 --- a/csharp/build/RunBenchmarks.bat +++ /dev/null @@ -1,2 +0,0 @@ -@echo off -CMD.exe /Q /C "CD %~dp0 && %WINDIR%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe /nologo build.csproj /toolsversion:4.0 /t:RunBenchmarks %1 %2 %3 %4 diff --git a/csharp/build/build.bat b/csharp/build/build.bat deleted file mode 100644 index bd7bd2a051429..0000000000000 --- a/csharp/build/build.bat +++ /dev/null @@ -1,20 +0,0 @@ -@echo off -SET BUILD_VERSION=%~1 -SET BUILD_TARGET=%~2 -SET BUILD_CONFIG=%~3 - -IF NOT "%BUILD_VERSION%"=="" GOTO RUN -ECHO. -ECHO Usage: build.bat platform [target] [config] [msbuild arguments] -ECHO. -ECHO - platform: CF20, CF35, NET20, NET35, NET40, PL40, SL20, SL30, or SL40 -ECHO - [target]: Rebuild, Clean, Build, Test, or Publish -ECHO - [config]: Debug or Release -ECHO. -EXIT /B 1 - -:RUN -IF "%BUILD_TARGET%"=="" SET BUILD_TARGET=Rebuild -IF "%BUILD_CONFIG%"=="" SET BUILD_CONFIG=Debug - -CMD.exe /Q /C "CD %~dp0 && %WINDIR%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe /nologo target.csproj /toolsversion:4.0 %4 %5 %6 "/t:%BUILD_TARGET%" "/p:Configuration=%BUILD_CONFIG%;TargetVersion=%BUILD_VERSION%" diff --git a/csharp/build/build.csproj b/csharp/build/build.csproj deleted file mode 100644 index e78b2efb449c4..0000000000000 --- a/csharp/build/build.csproj +++ /dev/null @@ -1,241 +0,0 @@ - - - - - - - - - - - - - - - - - - Protocol Buffers - Release - Any CPU - - - $(MSBuildProjectDirectory)\.. - $(ProjectDirectory)\src - $(ProjectDirectory)\lib - $(ProjectDirectory)\protos - - $(ProjectDirectory)\build_temp\GeneratedSource - $(ProjectDirectory)\build_temp - $(ProjectDirectory)\build_output - $(BuildOutputDirectory) - - /v2 /fast /formats - $(BuildTempDirectory)\..\BenchmarkResults.txt - $(ProjectDirectory)\benchmarks - - $(Configuration) - - - $(BuildOutputDirectory)\tools\protoc.exe - $(BuildOutputDirectory)\tools\protogen.exe - $(LibDirectory)\NUnit\tools\nunit-console.exe - $(LibDirectory)\CsProjectProjector\CsProjectProjector.exe - $(LibDirectory)\7-Zip 9.20\7za.exe - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - $(SourceDirectory)\ProtocolBuffers\DescriptorProtos - - - $(SourceDirectory)\ProtocolBuffers\DescriptorProtos - - - - - $(SourceDirectory)\AddressBook - - - - $(SourceDirectory)\ProtocolBuffers.Test\TestProtos - - - $(SourceDirectory)\ProtocolBuffers.Test\TestProtos - - - $(SourceDirectory)\ProtocolBuffers.Test\TestProtos - - - $(SourceDirectory)\ProtocolBuffers.Test\TestProtos - - - $(SourceDirectory)\ProtocolBuffers.Test\TestProtos - - - $(SourceDirectory)\ProtocolBuffers.Test\TestProtos - - - $(SourceDirectory)\ProtocolBuffers.Test\TestProtos - - - $(SourceDirectory)\ProtocolBuffers.Test\TestProtos - - - $(SourceDirectory)\ProtocolBuffers.Test\TestProtos - - - $(SourceDirectory)\ProtocolBuffers.Test\TestProtos - - - $(SourceDirectory)\ProtocolBuffers.Test\TestProtos - - - $(SourceDirectory)\ProtocolBuffers.Test\TestProtos - - - $(SourceDirectory)\ProtocolBuffers.Test\TestProtos - - - $(SourceDirectory)\ProtocolBuffers.Test\TestProtos - - - $(SourceDirectory)\ProtocolBuffersLite.Test\TestProtos - - - $(SourceDirectory)\ProtocolBuffers.Test\TestProtos - - - - $(SourceDirectory)\ProtocolBuffersLite.Test\TestProtos - - - $(SourceDirectory)\ProtocolBuffersLite.Test\TestProtos - - - $(SourceDirectory)\ProtocolBuffersLite.Test\TestProtos - - - $(SourceDirectory)\ProtocolBuffersLite.Test\TestProtos - - - $(SourceDirectory)\ProtocolBuffersLite.Test\TestProtos - - - $(SourceDirectory)\ProtocolBuffersLite.Test\TestProtos - - - $(SourceDirectory)\ProtocolBuffersLite.Test\TestProtos - - - $(SourceDirectory)\ProtocolBuffers.Test\TestProtos - - - $(SourceDirectory)\ProtocolBuffers.Test\TestProtos - - - $(SourceDirectory)\ProtoBench\TestProtos - - - $(SourceDirectory)\ProtoBench\TestProtos - - - $(SourceDirectory)\ProtoBench\TestProtos - - - $(SourceDirectory)\ProtoBench\TestProtos - - - - - - - - \protos\google\protobuf - - - \protos\google\protobuf\compiler - - - \protos\google\protobuf - - - \protos\tutorial - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/csharp/build/googlecode_upload.py b/csharp/build/googlecode_upload.py deleted file mode 100644 index d2d5f974cedab..0000000000000 --- a/csharp/build/googlecode_upload.py +++ /dev/null @@ -1,248 +0,0 @@ -#!/usr/bin/env python -# -# Copyright 2006, 2007 Google Inc. All Rights Reserved. -# Author: danderson@google.com (David Anderson) -# -# Script for uploading files to a Google Code project. -# -# This is intended to be both a useful script for people who want to -# streamline project uploads and a reference implementation for -# uploading files to Google Code projects. -# -# To upload a file to Google Code, you need to provide a path to the -# file on your local machine, a small summary of what the file is, a -# project name, and a valid account that is a member or owner of that -# project. You can optionally provide a list of labels that apply to -# the file. The file will be uploaded under the same name that it has -# in your local filesystem (that is, the "basename" or last path -# component). Run the script with '--help' to get the exact syntax -# and available options. -# -# Note that the upload script requests that you enter your -# googlecode.com password. This is NOT your Gmail account password! -# This is the password you use on googlecode.com for committing to -# Subversion and uploading files. You can find your password by going -# to http://code.google.com/hosting/settings when logged in with your -# Gmail account. If you have already committed to your project's -# Subversion repository, the script will automatically retrieve your -# credentials from there (unless disabled, see the output of '--help' -# for details). -# -# If you are looking at this script as a reference for implementing -# your own Google Code file uploader, then you should take a look at -# the upload() function, which is the meat of the uploader. You -# basically need to build a multipart/form-data POST request with the -# right fields and send it to https://PROJECT.googlecode.com/files . -# Authenticate the request using HTTP Basic authentication, as is -# shown below. -# -# Licensed under the terms of the Apache Software License 2.0: -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Questions, comments, feature requests and patches are most welcome. -# Please direct all of these to the Google Code users group: -# http://groups.google.com/group/google-code-hosting - -"""Google Code file uploader script. -""" - -__author__ = 'danderson@google.com (David Anderson)' - -import httplib -import os.path -import optparse -import getpass -import base64 -import sys - - -def upload(file, project_name, user_name, password, summary, labels=None): - """Upload a file to a Google Code project's file server. - - Args: - file: The local path to the file. - project_name: The name of your project on Google Code. - user_name: Your Google account name. - password: The googlecode.com password for your account. - Note that this is NOT your global Google Account password! - summary: A small description for the file. - labels: an optional list of label strings with which to tag the file. - - Returns: a tuple: - http_status: 201 if the upload succeeded, something else if an - error occured. - http_reason: The human-readable string associated with http_status - file_url: If the upload succeeded, the URL of the file on Google - Code, None otherwise. - """ - # The login is the user part of user@gmail.com. If the login provided - # is in the full user@domain form, strip it down. - if user_name.endswith('@gmail.com'): - user_name = user_name[:user_name.index('@gmail.com')] - - form_fields = [('summary', summary)] - if labels is not None: - form_fields.extend([('label', l.strip()) for l in labels]) - - content_type, body = encode_upload_request(form_fields, file) - - upload_host = '%s.googlecode.com' % project_name - upload_uri = '/files' - auth_token = base64.b64encode('%s:%s'% (user_name, password)) - headers = { - 'Authorization': 'Basic %s' % auth_token, - 'User-Agent': 'Googlecode.com uploader v0.9.4', - 'Content-Type': content_type, - } - - server = httplib.HTTPSConnection(upload_host) - server.request('POST', upload_uri, body, headers) - resp = server.getresponse() - server.close() - - if resp.status == 201: - location = resp.getheader('Location', None) - else: - location = None - return resp.status, resp.reason, location - - -def encode_upload_request(fields, file_path): - """Encode the given fields and file into a multipart form body. - - fields is a sequence of (name, value) pairs. file is the path of - the file to upload. The file will be uploaded to Google Code with - the same file name. - - Returns: (content_type, body) ready for httplib.HTTP instance - """ - BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla' - CRLF = '\r\n' - - body = [] - - # Add the metadata about the upload first - for key, value in fields: - body.extend( - ['--' + BOUNDARY, - 'Content-Disposition: form-data; name="%s"' % key, - '', - value, - ]) - - # Now add the file itself - file_name = os.path.basename(file_path) - f = open(file_path, 'rb') - file_content = f.read() - f.close() - - body.extend( - ['--' + BOUNDARY, - 'Content-Disposition: form-data; name="filename"; filename="%s"' - % file_name, - # The upload server determines the mime-type, no need to set it. - 'Content-Type: application/octet-stream', - '', - file_content, - ]) - - # Finalize the form body - body.extend(['--' + BOUNDARY + '--', '']) - - return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body) - - -def upload_find_auth(file_path, project_name, summary, labels=None, - user_name=None, password=None, tries=3): - """Find credentials and upload a file to a Google Code project's file server. - - file_path, project_name, summary, and labels are passed as-is to upload. - - Args: - file_path: The local path to the file. - project_name: The name of your project on Google Code. - summary: A small description for the file. - labels: an optional list of label strings with which to tag the file. - config_dir: Path to Subversion configuration directory, 'none', or None. - user_name: Your Google account name. - tries: How many attempts to make. - """ - - while tries > 0: - if user_name is None: - # Read username if not specified or loaded from svn config, or on - # subsequent tries. - sys.stdout.write('Please enter your googlecode.com username: ') - sys.stdout.flush() - user_name = sys.stdin.readline().rstrip() - if password is None: - # Read password if not loaded from svn config, or on subsequent tries. - print 'Please enter your googlecode.com password.' - print '** Note that this is NOT your Gmail account password! **' - print 'It is the password you use to access Subversion repositories,' - print 'and can be found here: http://code.google.com/hosting/settings' - password = getpass.getpass() - - status, reason, url = upload(file_path, project_name, user_name, password, - summary, labels) - # Returns 403 Forbidden instead of 401 Unauthorized for bad - # credentials as of 2007-07-17. - if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]: - # Rest for another try. - user_name = password = None - tries = tries - 1 - else: - # We're done. - break - - return status, reason, url - - -def main(): - parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY ' - '-p PROJECT [options] FILE') - parser.add_option('-s', '--summary', dest='summary', - help='Short description of the file') - parser.add_option('-p', '--project', dest='project', - help='Google Code project name') - parser.add_option('-u', '--user', dest='user', - help='Your Google Code username') - parser.add_option('-w', '--password', dest='password', - help='Your Google Code password') - parser.add_option('-l', '--labels', dest='labels', - help='An optional list of comma-separated labels to attach ' - 'to the file') - - options, args = parser.parse_args() - - if not options.summary: - parser.error('File summary is missing.') - elif not options.project: - parser.error('Project name is missing.') - elif len(args) < 1: - parser.error('File to upload not provided.') - elif len(args) > 1: - parser.error('Only one file may be specified.') - - file_path = args[0] - - if options.labels: - labels = options.labels.split(',') - else: - labels = None - - status, reason, url = upload_find_auth(file_path, options.project, - options.summary, labels, - options.user, options.password) - if url: - print 'The file was uploaded successfully.' - print 'URL: %s' % url - return 0 - else: - print 'An error occurred. Your file was not uploaded.' - print 'Google Code upload server said: %s (%s)' % (reason, status) - return 1 - - -if __name__ == '__main__': - sys.exit(main()) diff --git a/csharp/build/nuspec.xsd b/csharp/build/nuspec.xsd deleted file mode 100644 index db744d1a4fe1f..0000000000000 --- a/csharp/build/nuspec.xsd +++ /dev/null @@ -1,79 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/csharp/build/publish.csproj b/csharp/build/publish.csproj deleted file mode 100644 index bbe71df5a3a3f..0000000000000 --- a/csharp/build/publish.csproj +++ /dev/null @@ -1,186 +0,0 @@ - - - - - - - - - - - - - - Protocol Buffers - 2 - 4 - 1 - - - - protobuf-csharp-port- - false - - - - - - $(MSBuildProjectDirectory)\.. - $(ProjectDirectory)\build_temp - $(ProjectDirectory)\build_output - $(ProjectDirectory)\src - $(ProjectDirectory)\lib - - - $(ProjectDirectory)\release-key\Google.ProtocolBuffers.snk - - - hg.exe - C:\Python25\python.exe - $(registry:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v7.0A@InstallationFolder)Bin\sn.exe - $(LibDirectory)\StampVersion.exe - $(LibDirectory)\7-Zip 9.20\7za.exe - $(LibDirectory)\NuGet.exe - $(BuildOutputDirectory)\tools\protogen.exe - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - $(VersionMajor).$(VersionMinor).$(VersionBuild).$(VersionRevision) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - $(Python) "$(MSBuildProjectDirectory)\googlecode_upload.py" --project protobuf-csharp-port --user "$(GoogleUsername)" --password "$(GooglePassword)" - - $(BuildTempDirectory)\$(PackagePrefix)$(VersionLabel)-source.zip - $(BuildTempDirectory)\$(PackagePrefix)$(VersionLabel)-release-binaries.zip - $(BuildTempDirectory)\$(PackagePrefix)$(VersionLabel)-release-symbols.zip - $(BuildTempDirectory)\$(PackagePrefix)$(VersionLabel)-full-binaries.zip - $(BuildTempDirectory)\$(PackagePrefix)$(VersionLabel)-full-symbols.zip - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/csharp/build/target.csproj b/csharp/build/target.csproj deleted file mode 100644 index 09a9d50bd19db..0000000000000 --- a/csharp/build/target.csproj +++ /dev/null @@ -1,167 +0,0 @@ - - - - - - - - - - - - - - - Debug - Any CPU - NET20 - - - - $(MSBuildProjectDirectory)\.. - $(ProjectDirectory)\src - $(ProjectDirectory)\lib - - - $(ProjectDirectory)\build_temp\$(Configuration)\$(TargetVersion) - $(ProjectDirectory)\build_output\$(Configuration)\$(TargetVersion) - $(SourceDirectory)\ProtocolBuffersLibrary.$(TargetVersion).sln - - - $(LibDirectory)\NUnit\tools\nunit-console.exe - $(LibDirectory)\StatLight\tools\StatLight.exe - - - - - - 3.5 - NUNIT - v2.0 - - - 3.5 - NUNIT - v3.5 - - - 4.0 - NUNIT - v4.0 - - - 3.5 - NONE - v2.0 - - - 3.5 - NONE - v3.5 - - - 3.5 - SILVERLIGHT - v2.0 - - - 3.5 - SILVERLIGHT - v3.5 - - - 4.0 - SILVERLIGHT - v4.0 - - - 4.0 - SILVERLIGHT - v4.0 - $(ProjectDirectory)\build_output\$(Configuration)\portable-net40+sl4+sl5+wp7+wp8+win8 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/csharp/build_packages.bat b/csharp/build_packages.bat new file mode 100644 index 0000000000000..1502f0634b786 --- /dev/null +++ b/csharp/build_packages.bat @@ -0,0 +1,13 @@ +@rem Builds Google.Protobuf NuGet packages + +@rem Adjust the location of nuget.exe +set NUGET=C:\nuget\nuget.exe + +@rem Build src/Google.Protobuf.sln solution in Release configuration first. +%NUGET% pack src\Google.Protobuf\Google.Protobuf.nuspec -Symbols || goto :error + +goto :EOF + +:error +echo Failed! +exit /b %errorlevel% diff --git a/csharp/buildall.sh b/csharp/buildall.sh index 164707cbc00c2..45af705f38578 100755 --- a/csharp/buildall.sh +++ b/csharp/buildall.sh @@ -6,17 +6,12 @@ NUNIT_CONSOLE=nunit-console # The rest you can leave intact CONFIG=Release -KEYFILE=../keys/Google.ProtocolBuffers.snk # TODO(jtattermusch): signing! SRC=$(dirname $0)/src set -ex echo Building the solution. -xbuild /p:Configuration=$CONFIG $SRC/ProtocolBuffers.sln +xbuild /p:Configuration=$CONFIG $SRC/Google.Protobuf.sln echo Running tests. -$NUNIT_CONSOLE $SRC/ProtocolBuffers.Test/bin/$CONFIG/Google.ProtocolBuffers.Test.dll - -$NUNIT_CONSOLE $SRC/ProtocolBuffersLite.Test/bin/$CONFIG/Google.ProtocolBuffersLite.Test.dll - -$NUNIT_CONSOLE $SRC/ProtocolBuffersLite.Test/bin/$CONFIG/Google.ProtocolBuffersMixedLite.Test.dll +$NUNIT_CONSOLE $SRC/Google.Protobuf.Test/bin/$CONFIG/Google.Protobuf.Test.dll diff --git a/csharp/generate_protos.sh b/csharp/generate_protos.sh index 9e89bf26a9f54..962f2a9cd5f2d 100755 --- a/csharp/generate_protos.sh +++ b/csharp/generate_protos.sh @@ -23,10 +23,10 @@ cd $(dirname $0)/.. # Windows and Unix. if [ -z "$PROTOC" ]; then # TODO(jonskeet): Use an array and a for loop instead? - if [ -x vsprojects/Debug/protoc.exe ]; then - PROTOC=vsprojects/Debug/protoc.exe - elif [ -x vsprojects/Release/protoc.exe ]; then - PROTOC=vsprojects/Release/protoc.exe + if [ -x cmake/build/Debug/protoc.exe ]; then + PROTOC=cmake/build/Debug/protoc.exe + elif [ -x cmake/build/Release/protoc.exe ]; then + PROTOC=cmake/build/Release/protoc.exe elif [ -x src/protoc ]; then PROTOC=src/protoc else @@ -38,56 +38,36 @@ fi # Descriptor proto # TODO(jonskeet): Remove fixup cp src/google/protobuf/descriptor.proto src/google/protobuf/descriptor_proto_file.proto -$PROTOC -Isrc --csharp_out=csharp/src/ProtocolBuffers/DescriptorProtos \ +$PROTOC -Isrc --csharp_out=csharp/src/Google.Protobuf/Reflection \ src/google/protobuf/descriptor_proto_file.proto rm src/google/protobuf/descriptor_proto_file.proto +$PROTOC -Isrc --csharp_out=csharp/src/Google.Protobuf/WellKnownTypes \ + src/google/protobuf/any.proto \ + src/google/protobuf/api.proto \ + src/google/protobuf/duration.proto \ + src/google/protobuf/empty.proto \ + src/google/protobuf/field_mask.proto \ + src/google/protobuf/source_context.proto \ + src/google/protobuf/struct.proto \ + src/google/protobuf/timestamp.proto \ + src/google/protobuf/type.proto \ + src/google/protobuf/wrappers.proto -# ProtocolBuffers.Test protos -$PROTOC -Isrc --csharp_out=csharp/src/ProtocolBuffers.Test/TestProtos \ - src/google/protobuf/unittest.proto \ - src/google/protobuf/unittest_custom_options.proto \ - src/google/protobuf/unittest_drop_unknown_fields.proto \ - src/google/protobuf/unittest_enormous_descriptor.proto \ - src/google/protobuf/unittest_import.proto \ - src/google/protobuf/unittest_import_public.proto \ - src/google/protobuf/unittest_mset.proto \ - src/google/protobuf/unittest_optimize_for.proto \ - src/google/protobuf/unittest_no_field_presence.proto \ - src/google/protobuf/unknown_enum_test.proto +$PROTOC -Isrc --csharp_out=csharp/src/Google.Protobuf.Test/TestProtos \ + src/google/protobuf/map_unittest_proto3.proto \ + src/google/protobuf/unittest_proto3.proto \ + src/google/protobuf/unittest_import_proto3.proto \ + src/google/protobuf/unittest_import_public_proto3.proto \ + src/google/protobuf/unittest_well_known_types.proto -$PROTOC -Icsharp/protos/extest --csharp_out=csharp/src/ProtocolBuffers.Test/TestProtos \ - csharp/protos/extest/unittest_extras_xmltest.proto \ - csharp/protos/extest/unittest_issues.proto -$PROTOC -Ibenchmarks --csharp_out=csharp/src/ProtocolBuffers.Test/TestProtos \ - benchmarks/google_size.proto \ - benchmarks/google_speed.proto - -# ProtocolBuffersLite.Test protos -$PROTOC -Isrc --csharp_out=csharp/src/ProtocolBuffersLite.Test/TestProtos \ - src/google/protobuf/unittest.proto \ - src/google/protobuf/unittest_import.proto \ - src/google/protobuf/unittest_import_lite.proto \ - src/google/protobuf/unittest_import_public.proto \ - src/google/protobuf/unittest_import_public_lite.proto \ - src/google/protobuf/unittest_lite.proto \ - src/google/protobuf/unittest_lite_imports_nonlite.proto - -$PROTOC -Icsharp/protos/extest --csharp_out=csharp/src/ProtocolBuffersLite.Test/TestProtos \ - csharp/protos/extest/unittest_extras_full.proto \ - csharp/protos/extest/unittest_extras_lite.proto - -# TODO(jonskeet): Remove fixup; see issue #307 -sed -i -e 's/RepeatedFieldsGenerator\.Group/RepeatedFieldsGenerator.Types.Group/g' \ - csharp/src/ProtocolBuffers.Test/TestProtos/Unittest.cs \ - csharp/src/ProtocolBuffersLite.Test/TestProtos/Unittest.cs \ - csharp/src/ProtocolBuffersLite.Test/TestProtos/UnittestLite.cs - -# TODO(jonskeet): Remove fixup -sed -i -e 's/DescriptorProtos\.Descriptor\./DescriptorProtos.DescriptorProtoFile./g' \ - csharp/src/ProtocolBuffers.Test/TestProtos/UnittestCustomOptions.cs +$PROTOC -Icsharp/protos --csharp_out=csharp/src/Google.Protobuf.Test/TestProtos \ + csharp/protos/unittest_issues.proto # AddressBook sample protos $PROTOC -Iexamples --csharp_out=csharp/src/AddressBook \ examples/addressbook.proto + +$PROTOC -Iconformance --csharp_out=csharp/src/Google.Protobuf.Conformance \ + conformance/conformance.proto diff --git a/csharp/keys/Google.Protobuf.public.snk b/csharp/keys/Google.Protobuf.public.snk new file mode 100644 index 0000000000000..59cd36985f227 Binary files /dev/null and b/csharp/keys/Google.Protobuf.public.snk differ diff --git a/csharp/keys/Google.ProtocolBuffers.snk b/csharp/keys/Google.ProtocolBuffers.snk deleted file mode 100644 index 6bbfc90fee515..0000000000000 Binary files a/csharp/keys/Google.ProtocolBuffers.snk and /dev/null differ diff --git a/csharp/keys/README.md b/csharp/keys/README.md new file mode 100644 index 0000000000000..1a0141982c9f0 --- /dev/null +++ b/csharp/keys/README.md @@ -0,0 +1,5 @@ +Contents +-------- + +- Google.Protobuf.public.snk: + Public key to verify strong name of Google.Protobuf assemblies. \ No newline at end of file diff --git a/csharp/keys/generate_new_key.bat b/csharp/keys/generate_new_key.bat deleted file mode 100644 index 9f99c07746bc7..0000000000000 --- a/csharp/keys/generate_new_key.bat +++ /dev/null @@ -1,13 +0,0 @@ -@ECHO OFF -IF EXIST "C:\Program Files\Microsoft SDKs\Windows\v7.0\Bin\sn.exe" GOTO FOUND -goto USEPATH - -:FOUND -"C:\Program Files\Microsoft SDKs\Windows\v7.0\Bin\sn.exe" -k %~dp0\Google.ProtocolBuffers.snk -GOTO EXIT - -:USEPATH -sn.exe -k %~dp0\Google.ProtocolBuffers.snk -GOTO EXIT - -:EXIT \ No newline at end of file diff --git a/csharp/protos/extest/unittest_extras_full.proto b/csharp/protos/extest/unittest_extras_full.proto deleted file mode 100644 index 1b54605376db9..0000000000000 --- a/csharp/protos/extest/unittest_extras_full.proto +++ /dev/null @@ -1,71 +0,0 @@ -syntax = "proto2"; - -package protobuf_unittest_extra; - -option csharp_namespace = "Google.ProtocolBuffers.TestProtos"; -option optimize_for = CODE_SIZE; -option java_package = "com.google.protobuf"; - -message TestInteropPerson { - required string name = 1; - required int32 id = 2; - optional string email = 3; - repeated int32 codes = 10 [packed=true]; - - enum PhoneType { - MOBILE = 0; - HOME = 1; - WORK = 2; - } - - message PhoneNumber { - required string number = 1; - optional PhoneType type = 2 [default = HOME]; - } - - repeated PhoneNumber phone = 4; - - repeated group Addresses = 5 { - required string address = 1; - optional string address2 = 2; - required string city = 3; - required string state = 4; - required fixed32 zip = 5; - } - - extensions 100 to 199; -} - -message TestInteropEmployeeId { - required string number = 1; -} - -extend TestInteropPerson { - // Note: changed from required to optional, as required fields are not - // permitted in extensions. (The fact that this was allowed in protogen - // before was almost certainly a bug.) - optional TestInteropEmployeeId employee_id = 126; -} - -message TestMissingFieldsA { - required string name = 1; - required int32 id = 2; - optional string email = 3; - - message SubA { - required int32 count = 5; - repeated string values = 6; - } - optional SubA testA = 11; -} - -message TestMissingFieldsB { - required string name = 1; - required int32 id = 2; - optional string website = 4; - - message SubB { - repeated string values = 7; - } - optional SubB testB = 12; -} diff --git a/csharp/protos/extest/unittest_extras_lite.proto b/csharp/protos/extest/unittest_extras_lite.proto deleted file mode 100644 index 0c242d2fa6660..0000000000000 --- a/csharp/protos/extest/unittest_extras_lite.proto +++ /dev/null @@ -1,115 +0,0 @@ -syntax = "proto2"; - -package protobuf_unittest_extra; - -option csharp_namespace = "Google.ProtocolBuffers.TestProtos"; -option optimize_for = LITE_RUNTIME; -option java_package = "com.google.protobuf"; - -message TestRequiredLite { - required int32 d = 1; - required ExtraEnum en = 2 [default = DEFAULT]; -} - -enum ExtraEnum { - DEFAULT = 10; - EXLITE_FOO = 7; - EXLITE_BAR = 8; - EXLITE_BAZ = 9; -} - -message TestInteropPersonLite { - required string name = 1; - required int32 id = 2; - optional string email = 3; - repeated int32 codes = 10 [packed=true]; - - enum PhoneType { - MOBILE = 0; - HOME = 1; - WORK = 2; - } - - message PhoneNumber { - required string number = 1; - optional PhoneType type = 2 [default = HOME]; - } - - repeated PhoneNumber phone = 4; - - repeated group Addresses = 5 { - required string address = 1; - optional string address2 = 2; - required string city = 3; - required string state = 4; - required fixed32 zip = 5; - } - - extensions 100 to 199; -} - -message TestInteropEmployeeIdLite { - required string number = 1; -} - -extend TestInteropPersonLite { - // Note: changed from required to optional, as required fields are not - // permitted in extensions. (The fact that this was allowed in protogen - // before was almost certainly a bug.) - optional TestInteropEmployeeIdLite employee_id_lite = 126; -} - -/* Removed from unittest_lite.proto and added back here */ - -message TestUnpackedExtensionsLite { - extensions 1 to max; -} - -message TestUnpackedTypesLite { - repeated int32 unpacked_int32 = 90; - repeated int64 unpacked_int64 = 91; - repeated uint32 unpacked_uint32 = 92; - repeated uint64 unpacked_uint64 = 93; - repeated sint32 unpacked_sint32 = 94; - repeated sint64 unpacked_sint64 = 95; - repeated fixed32 unpacked_fixed32 = 96; - repeated fixed64 unpacked_fixed64 = 97; - repeated sfixed32 unpacked_sfixed32 = 98; - repeated sfixed64 unpacked_sfixed64 = 99; - repeated float unpacked_float = 100; - repeated double unpacked_double = 101; - repeated bool unpacked_bool = 102; - repeated UnpackedTypesForeignEnumLite unpacked_enum = 103; -} - -extend TestUnpackedExtensionsLite { - repeated int32 unpacked_int32_extension_lite = 90; - repeated int64 unpacked_int64_extension_lite = 91; - repeated uint32 unpacked_uint32_extension_lite = 92; - repeated uint64 unpacked_uint64_extension_lite = 93; - repeated sint32 unpacked_sint32_extension_lite = 94; - repeated sint64 unpacked_sint64_extension_lite = 95; - repeated fixed32 unpacked_fixed32_extension_lite = 96; - repeated fixed64 unpacked_fixed64_extension_lite = 97; - repeated sfixed32 unpacked_sfixed32_extension_lite = 98; - repeated sfixed64 unpacked_sfixed64_extension_lite = 99; - repeated float unpacked_float_extension_lite = 100; - repeated double unpacked_double_extension_lite = 101; - repeated bool unpacked_bool_extension_lite = 102; - repeated UnpackedTypesForeignEnumLite unpacked_enum_extension_lite = 103; -} - -enum UnpackedTypesForeignEnumLite { - FOREIGN_LITE_FOO = 4; - FOREIGN_LITE_BAR = 5; - FOREIGN_LITE_BAZ = 6; -} - -message BucketOfBytes { - optional bytes value = 1; - -} -message BucketOfBytesEx { - optional bytes value = 1; - optional bytes value2 = 255; -} \ No newline at end of file diff --git a/csharp/protos/extest/unittest_extras_xmltest.proto b/csharp/protos/extest/unittest_extras_xmltest.proto deleted file mode 100644 index fae3616537121..0000000000000 --- a/csharp/protos/extest/unittest_extras_xmltest.proto +++ /dev/null @@ -1,53 +0,0 @@ -syntax = "proto2"; - -option csharp_namespace = "Google.ProtocolBuffers.TestProtos"; - -package protobuf_unittest_extra; - -option optimize_for = SPEED; - -enum EnumOptions { - ONE = 0; - TWO = 1; - THREE = 2; -} - -message TestXmlChild { - repeated EnumOptions options = 3; - optional bytes binary = 4; -} - -message TestXmlNoFields { -} - -message TestXmlRescursive { - optional TestXmlRescursive child = 1; -} - -message TestXmlMessage { - - optional int64 number = 6; - repeated int32 numbers = 2; - optional string text = 3; - repeated string textlines = 700; - optional bool valid = 5; - - optional TestXmlChild child = 1; - repeated group Children = 401 { - repeated EnumOptions options = 3; - optional bytes binary = 4; - } - -extensions 100 to 199; -} - -message TestXmlExtension { - required int32 number = 1; -} - -extend TestXmlMessage { - optional EnumOptions extension_enum = 101; - optional string extension_text = 102; - repeated int32 extension_number = 103 [packed = true]; - optional TestXmlExtension extension_message = 199; -} diff --git a/csharp/protos/extest/unittest_issues.proto b/csharp/protos/extest/unittest_issues.proto deleted file mode 100644 index 97249dff71c10..0000000000000 --- a/csharp/protos/extest/unittest_issues.proto +++ /dev/null @@ -1,141 +0,0 @@ -syntax = "proto2"; - -// 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. - -// Issue: Non-"Google.Protobuffers" namespace will ensure that protobuffer library types are qualified -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 - -// message A { -// optional int32 _A = 1; -// } - -// message B { -// optional int32 B_ = 1; -// } - -//message AB { -// optional int32 a_b = 1; -//} - -// Similar issue with numeric names -// Java code failed too, so probably best for this to be a restriction. -// See https://github.com/google/protobuf/issues/308 -// message NumberField { -// 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 { - FiveBelow = -5; - MinusOne = -1; - Zero = 0; -} - -message NegativeEnumMessage { - optional NegativeEnum value = 1; - repeated NegativeEnum values = 2; - repeated NegativeEnum packed_values = 3 [packed=true]; -} - -// Issue 21: http://code.google.com/p/protobuf-csharp-port/issues/detail?id=21 -// Decorate fields with [deprecated=true] as [System.Obsolete] - -message DeprecatedChild { -} - -enum DeprecatedEnum { - one = 1; -} - -message DeprecatedFieldsMessage { - optional int32 PrimitiveValue = 1 [deprecated = true]; - repeated int32 PrimitiveArray = 2 [deprecated = true]; - - optional DeprecatedChild MessageValue = 3 [deprecated = true]; - repeated DeprecatedChild MessageArray = 4 [deprecated = true]; - - optional 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; -} diff --git a/csharp/protos/unittest_issues.proto b/csharp/protos/unittest_issues.proto new file mode 100644 index 0000000000000..989b3dc426e9c --- /dev/null +++ b/csharp/protos/unittest_issues.proto @@ -0,0 +1,119 @@ +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. + +// Issue: Non-"Google.Protobuffers" namespace will ensure that protobuffer library types are qualified +option csharp_namespace = "UnitTest.Issues.TestProtos"; + +package unittest_issues; +option optimize_for = SPEED; + +// Issue 307: when generating doubly-nested types, any references +// should be of the form A.Types.B.Types.C. +message Issue307 { + message NestedOnce { + message NestedTwice { + } + } +} + +// 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 + +// message A { +// optional int32 _A = 1; +// } + +// message B { +// optional int32 B_ = 1; +// } + +//message AB { +// optional int32 a_b = 1; +//} + +// Similar issue with numeric names +// Java code failed too, so probably best for this to be a restriction. +// See https://github.com/google/protobuf/issues/308 +// message NumberField { +// optional int32 _01 = 1; +// } + +// issue 19 - negative enum values + +enum NegativeEnum { + NEGATIVE_ENUM_ZERO = 0; + FiveBelow = -5; + MinusOne = -1; +} + +message NegativeEnumMessage { + NegativeEnum value = 1; + repeated NegativeEnum values = 2 [packed = false]; + repeated NegativeEnum packed_values = 3 [packed=true]; +} + +// Issue 21: http://code.google.com/p/protobuf-csharp-port/issues/detail?id=21 +// Decorate fields with [deprecated=true] as [System.Obsolete] + +message DeprecatedChild { +} + +enum DeprecatedEnum { + DEPRECATED_ZERO = 0; + one = 1; +} + +message DeprecatedFieldsMessage { + int32 PrimitiveValue = 1 [deprecated = true]; + repeated int32 PrimitiveArray = 2 [deprecated = true]; + + DeprecatedChild MessageValue = 3 [deprecated = true]; + repeated DeprecatedChild MessageArray = 4 [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 { + int32 item = 1; +} + +message ReservedNames { + // Force a nested type called Types + message SomeNestedType { + } + + int32 types = 1; + int32 descriptor = 2; +} + +message TestJsonFieldOrdering { + // These fields are deliberately not declared in numeric + // order, and the oneof fields aren't contiguous either. + // This allows for reasonably robust tests of JSON output + // ordering. + // TestFieldOrderings in unittest_proto3.proto is similar, + // but doesn't include oneofs. + // TODO: Consider adding oneofs to TestFieldOrderings, although + // that will require fixing other tests in multiple platforms. + // Alternatively, consider just adding this to + // unittest_proto3.proto if multiple platforms want it. + + int32 plain_int32 = 4; + + oneof o1 { + string o1_string = 2; + int32 o1_int32 = 5; + } + + string plain_string = 1; + + oneof o2 { + int32 o2_int32 = 6; + string o2_string = 3; + } + +} \ No newline at end of file diff --git a/csharp/src/AddressBook/AddPerson.cs b/csharp/src/AddressBook/AddPerson.cs index 462b0c5647aa9..6eeb9f6e849db 100644 --- a/csharp/src/AddressBook/AddPerson.cs +++ b/csharp/src/AddressBook/AddPerson.cs @@ -1,10 +1,7 @@ #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/ +// 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 @@ -31,13 +28,12 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - #endregion using System; using System.IO; -namespace Google.ProtocolBuffers.Examples.AddressBook +namespace Google.Protobuf.Examples.AddressBook { internal class AddPerson { @@ -46,7 +42,7 @@ internal class AddPerson /// private static Person PromptForAddress(TextReader input, TextWriter output) { - Person.Builder person = Person.CreateBuilder(); + Person person = new Person(); output.Write("Enter person ID: "); person.Id = int.Parse(input.ReadLine()); @@ -70,8 +66,7 @@ private static Person PromptForAddress(TextReader input, TextWriter output) break; } - Person.Types.PhoneNumber.Builder phoneNumber = - Person.Types.PhoneNumber.CreateBuilder().SetNumber(number); + Person.Types.PhoneNumber phoneNumber = new Person.Types.PhoneNumber { Number = number }; output.Write("Is this a mobile, home, or work phone? "); String type = input.ReadLine(); @@ -91,9 +86,9 @@ private static Person PromptForAddress(TextReader input, TextWriter output) break; } - person.AddPhone(phoneNumber); + person.Phones.Add(phoneNumber); } - return person.Build(); + return person; } /// @@ -108,27 +103,28 @@ public static int Main(string[] args) return -1; } - AddressBook.Builder addressBook = AddressBook.CreateBuilder(); + AddressBook addressBook; if (File.Exists(args[0])) { using (Stream file = File.OpenRead(args[0])) { - addressBook.MergeFrom(file); + addressBook = AddressBook.Parser.ParseFrom(file); } } else { Console.WriteLine("{0}: File not found. Creating a new file.", args[0]); + addressBook = new AddressBook(); } // Add an address. - addressBook.AddPerson(PromptForAddress(Console.In, Console.Out)); + addressBook.People.Add(PromptForAddress(Console.In, Console.Out)); // Write the new address book back to disk. using (Stream output = File.OpenWrite(args[0])) { - addressBook.Build().WriteTo(output); + addressBook.WriteTo(output); } return 0; } diff --git a/csharp/src/AddressBook/AddressBook.csproj b/csharp/src/AddressBook/AddressBook.csproj index f7e0d6be2d43b..8f8ca7e23a496 100644 --- a/csharp/src/AddressBook/AddressBook.csproj +++ b/csharp/src/AddressBook/AddressBook.csproj @@ -8,12 +8,13 @@ {A31F5FB2-4FF3-432A-B35B-5CD203606311} Exe Properties - Google.ProtocolBuffers.Examples.AddressBook + Google.Protobuf.Examples.AddressBook AddressBook - v4.0 + v4.5 512 - Google.ProtocolBuffers.Examples.AddressBook.Program - Client + Google.Protobuf.Examples.AddressBook.Program + + true @@ -26,6 +27,7 @@ 4 true Off + false pdbonly @@ -37,6 +39,7 @@ 4 true Off + false @@ -53,9 +56,9 @@ - + {6908BDCE-D925-43F3-94AC-A531E6DF2591} - ProtocolBuffers + Google.Protobuf diff --git a/csharp/src/AddressBook/Addressbook.cs b/csharp/src/AddressBook/Addressbook.cs index 58ad28ad5d232..f2be5baeb7a90 100644 --- a/csharp/src/AddressBook/Addressbook.cs +++ b/csharp/src/AddressBook/Addressbook.cs @@ -3,1152 +3,448 @@ #pragma warning disable 1591, 0612, 3021 #region Designer generated code -using pb = global::Google.ProtocolBuffers; -using pbc = global::Google.ProtocolBuffers.Collections; -using pbd = global::Google.ProtocolBuffers.Descriptors; +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; -namespace Google.ProtocolBuffers.Examples.AddressBook { +namespace Google.Protobuf.Examples.AddressBook { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class Addressbook { - #region Extension registration - public static void RegisterAllExtensions(pb::ExtensionRegistry registry) { - } - #endregion - #region Static variables - internal static pbd::MessageDescriptor internal__static_tutorial_Person__Descriptor; - internal static pb::FieldAccess.FieldAccessorTable internal__static_tutorial_Person__FieldAccessorTable; - internal static pbd::MessageDescriptor internal__static_tutorial_Person_PhoneNumber__Descriptor; - internal static pb::FieldAccess.FieldAccessorTable internal__static_tutorial_Person_PhoneNumber__FieldAccessorTable; - internal static pbd::MessageDescriptor internal__static_tutorial_AddressBook__Descriptor; - internal static pb::FieldAccess.FieldAccessorTable internal__static_tutorial_AddressBook__FieldAccessorTable; - #endregion #region Descriptor - public static pbd::FileDescriptor Descriptor { + public static pbr::FileDescriptor Descriptor { get { return descriptor; } } - private static pbd::FileDescriptor descriptor; + private static pbr::FileDescriptor descriptor; static Addressbook() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( - "ChFhZGRyZXNzYm9vay5wcm90bxIIdHV0b3JpYWwi2gEKBlBlcnNvbhIMCgRu", - "YW1lGAEgAigJEgoKAmlkGAIgAigFEg0KBWVtYWlsGAMgASgJEisKBXBob25l", - "GAQgAygLMhwudHV0b3JpYWwuUGVyc29uLlBob25lTnVtYmVyGk0KC1Bob25l", - "TnVtYmVyEg4KBm51bWJlchgBIAIoCRIuCgR0eXBlGAIgASgOMhoudHV0b3Jp", - "YWwuUGVyc29uLlBob25lVHlwZToESE9NRSIrCglQaG9uZVR5cGUSCgoGTU9C", - "SUxFEAASCAoESE9NRRABEggKBFdPUksQAiIvCgtBZGRyZXNzQm9vaxIgCgZw", - "ZXJzb24YASADKAsyEC50dXRvcmlhbC5QZXJzb25CVwoUY29tLmV4YW1wbGUu", - "dHV0b3JpYWxCEUFkZHJlc3NCb29rUHJvdG9zqgIrR29vZ2xlLlByb3RvY29s", - "QnVmZmVycy5FeGFtcGxlcy5BZGRyZXNzQm9vaw==")); - pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) { - descriptor = root; - internal__static_tutorial_Person__Descriptor = Descriptor.MessageTypes[0]; - internal__static_tutorial_Person__FieldAccessorTable = - new pb::FieldAccess.FieldAccessorTable(internal__static_tutorial_Person__Descriptor, - new string[] { "Name", "Id", "Email", "Phone", }); - internal__static_tutorial_Person_PhoneNumber__Descriptor = internal__static_tutorial_Person__Descriptor.NestedTypes[0]; - internal__static_tutorial_Person_PhoneNumber__FieldAccessorTable = - new pb::FieldAccess.FieldAccessorTable(internal__static_tutorial_Person_PhoneNumber__Descriptor, - new string[] { "Number", "Type", }); - internal__static_tutorial_AddressBook__Descriptor = Descriptor.MessageTypes[1]; - internal__static_tutorial_AddressBook__FieldAccessorTable = - new pb::FieldAccess.FieldAccessorTable(internal__static_tutorial_AddressBook__Descriptor, - new string[] { "Person", }); - pb::ExtensionRegistry registry = pb::ExtensionRegistry.CreateInstance(); - RegisterAllExtensions(registry); - return registry; - }; - pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, - new pbd::FileDescriptor[] { - }, assigner); + "ChFhZGRyZXNzYm9vay5wcm90bxIIdHV0b3JpYWwi1QEKBlBlcnNvbhIMCgRu", + "YW1lGAEgASgJEgoKAmlkGAIgASgFEg0KBWVtYWlsGAMgASgJEiwKBnBob25l", + "cxgEIAMoCzIcLnR1dG9yaWFsLlBlcnNvbi5QaG9uZU51bWJlchpHCgtQaG9u", + "ZU51bWJlchIOCgZudW1iZXIYASABKAkSKAoEdHlwZRgCIAEoDjIaLnR1dG9y", + "aWFsLlBlcnNvbi5QaG9uZVR5cGUiKwoJUGhvbmVUeXBlEgoKBk1PQklMRRAA", + "EggKBEhPTUUQARIICgRXT1JLEAIiLwoLQWRkcmVzc0Jvb2sSIAoGcGVvcGxl", + "GAEgAygLMhAudHV0b3JpYWwuUGVyc29uQlAKFGNvbS5leGFtcGxlLnR1dG9y", + "aWFsQhFBZGRyZXNzQm9va1Byb3Rvc6oCJEdvb2dsZS5Qcm90b2J1Zi5FeGFt", + "cGxlcy5BZGRyZXNzQm9va2IGcHJvdG8z")); + descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] { + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.Examples.AddressBook.Person), new[]{ "Name", "Id", "Email", "Phones" }, null, new[]{ typeof(global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneType) }, new pbr::GeneratedCodeInfo[] { new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneNumber), new[]{ "Number", "Type" }, null, null, null)}), + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.Examples.AddressBook.AddressBook), new[]{ "People" }, null, null, null) + })); } #endregion } #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class Person : pb::GeneratedMessage { - private Person() { } - private static readonly Person defaultInstance = new Person().MakeReadOnly(); - private static readonly string[] _personFieldNames = new string[] { "email", "id", "name", "phone" }; - private static readonly uint[] _personFieldTags = new uint[] { 26, 16, 10, 34 }; - public static Person DefaultInstance { - get { return defaultInstance; } - } - - public override Person DefaultInstanceForType { - get { return DefaultInstance; } - } + public sealed partial class Person : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Person()); + public static pb::MessageParser Parser { get { return _parser; } } - protected override Person ThisMessage { - get { return this; } + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Examples.AddressBook.Addressbook.Descriptor.MessageTypes[0]; } } - public static pbd::MessageDescriptor Descriptor { - get { return global::Google.ProtocolBuffers.Examples.AddressBook.Addressbook.internal__static_tutorial_Person__Descriptor; } + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } } - protected override pb::FieldAccess.FieldAccessorTable InternalFieldAccessors { - get { return global::Google.ProtocolBuffers.Examples.AddressBook.Addressbook.internal__static_tutorial_Person__FieldAccessorTable; } + public Person() { + OnConstruction(); } - #region Nested types - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public static partial class Types { - public enum PhoneType { - MOBILE = 0, - HOME = 1, - WORK = 2, - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class PhoneNumber : pb::GeneratedMessage { - private PhoneNumber() { } - private static readonly PhoneNumber defaultInstance = new PhoneNumber().MakeReadOnly(); - private static readonly string[] _phoneNumberFieldNames = new string[] { "number", "type" }; - private static readonly uint[] _phoneNumberFieldTags = new uint[] { 10, 16 }; - public static PhoneNumber DefaultInstance { - get { return defaultInstance; } - } - - public override PhoneNumber DefaultInstanceForType { - get { return DefaultInstance; } - } - - protected override PhoneNumber ThisMessage { - get { return this; } - } - - public static pbd::MessageDescriptor Descriptor { - get { return global::Google.ProtocolBuffers.Examples.AddressBook.Addressbook.internal__static_tutorial_Person_PhoneNumber__Descriptor; } - } - - protected override pb::FieldAccess.FieldAccessorTable InternalFieldAccessors { - get { return global::Google.ProtocolBuffers.Examples.AddressBook.Addressbook.internal__static_tutorial_Person_PhoneNumber__FieldAccessorTable; } - } - - public const int NumberFieldNumber = 1; - private bool hasNumber; - private string number_ = ""; - public bool HasNumber { - get { return hasNumber; } - } - public string Number { - get { return number_; } - } - - public const int TypeFieldNumber = 2; - private bool hasType; - private global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType type_ = global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType.HOME; - public bool HasType { - get { return hasType; } - } - public global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType Type { - get { return type_; } - } - - public override bool IsInitialized { - get { - if (!hasNumber) return false; - return true; - } - } - - public override void WriteTo(pb::ICodedOutputStream output) { - CalcSerializedSize(); - string[] field_names = _phoneNumberFieldNames; - if (hasNumber) { - output.WriteString(1, field_names[0], Number); - } - if (hasType) { - output.WriteEnum(2, field_names[1], (int) Type, Type); - } - UnknownFields.WriteTo(output); - } - - private int memoizedSerializedSize = -1; - public override int SerializedSize { - get { - int size = memoizedSerializedSize; - if (size != -1) return size; - return CalcSerializedSize(); - } - } - - private int CalcSerializedSize() { - int size = memoizedSerializedSize; - if (size != -1) return size; - - size = 0; - if (hasNumber) { - size += pb::CodedOutputStream.ComputeStringSize(1, Number); - } - if (hasType) { - size += pb::CodedOutputStream.ComputeEnumSize(2, (int) Type); - } - size += UnknownFields.SerializedSize; - memoizedSerializedSize = size; - return size; - } - public static PhoneNumber ParseFrom(pb::ByteString data) { - return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static PhoneNumber ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { - return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static PhoneNumber ParseFrom(byte[] data) { - return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static PhoneNumber ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { - return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static PhoneNumber ParseFrom(global::System.IO.Stream input) { - return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static PhoneNumber ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { - return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - public static PhoneNumber ParseDelimitedFrom(global::System.IO.Stream input) { - return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); - } - public static PhoneNumber ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { - return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); - } - public static PhoneNumber ParseFrom(pb::ICodedInputStream input) { - return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static PhoneNumber ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { - return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - private PhoneNumber MakeReadOnly() { - return this; - } - - public static Builder CreateBuilder() { return new Builder(); } - public override Builder ToBuilder() { return CreateBuilder(this); } - public override Builder CreateBuilderForType() { return new Builder(); } - public static Builder CreateBuilder(PhoneNumber prototype) { - return new Builder(prototype); - } - - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class Builder : pb::GeneratedBuilder { - protected override Builder ThisBuilder { - get { return this; } - } - public Builder() { - result = DefaultInstance; - resultIsReadOnly = true; - } - internal Builder(PhoneNumber cloneFrom) { - result = cloneFrom; - resultIsReadOnly = true; - } - - private bool resultIsReadOnly; - private PhoneNumber result; - - private PhoneNumber PrepareBuilder() { - if (resultIsReadOnly) { - PhoneNumber original = result; - result = new PhoneNumber(); - resultIsReadOnly = false; - MergeFrom(original); - } - return result; - } - - public override bool IsInitialized { - get { return result.IsInitialized; } - } - - protected override PhoneNumber MessageBeingBuilt { - get { return PrepareBuilder(); } - } - - public override Builder Clear() { - result = DefaultInstance; - resultIsReadOnly = true; - return this; - } + partial void OnConstruction(); - public override Builder Clone() { - if (resultIsReadOnly) { - return new Builder(result); - } else { - return new Builder().MergeFrom(result); - } - } - - public override pbd::MessageDescriptor DescriptorForType { - get { return global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.Descriptor; } - } - - public override PhoneNumber DefaultInstanceForType { - get { return global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.DefaultInstance; } - } - - public override PhoneNumber BuildPartial() { - if (resultIsReadOnly) { - return result; - } - resultIsReadOnly = true; - return result.MakeReadOnly(); - } - - public override Builder MergeFrom(pb::IMessage other) { - if (other is PhoneNumber) { - return MergeFrom((PhoneNumber) other); - } else { - base.MergeFrom(other); - return this; - } - } - - public override Builder MergeFrom(PhoneNumber other) { - if (other == global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.DefaultInstance) return this; - PrepareBuilder(); - if (other.HasNumber) { - Number = other.Number; - } - if (other.HasType) { - Type = other.Type; - } - this.MergeUnknownFields(other.UnknownFields); - return this; - } - - public override Builder MergeFrom(pb::ICodedInputStream input) { - return MergeFrom(input, pb::ExtensionRegistry.Empty); - } - - public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { - PrepareBuilder(); - pb::UnknownFieldSet.Builder unknownFields = null; - uint tag; - string field_name; - while (input.ReadTag(out tag, out field_name)) { - if(tag == 0 && field_name != null) { - int field_ordinal = global::System.Array.BinarySearch(_phoneNumberFieldNames, field_name, global::System.StringComparer.Ordinal); - if(field_ordinal >= 0) - tag = _phoneNumberFieldTags[field_ordinal]; - else { - if (unknownFields == null) { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - continue; - } - } - switch (tag) { - case 0: { - throw pb::InvalidProtocolBufferException.InvalidTag(); - } - default: { - if (pb::WireFormat.IsEndGroupTag(tag)) { - if (unknownFields != null) { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - if (unknownFields == null) { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - break; - } - case 10: { - result.hasNumber = input.ReadString(ref result.number_); - break; - } - case 16: { - object unknown; - if(input.ReadEnum(ref result.type_, out unknown)) { - result.hasType = true; - } else if(unknown is int) { - if (unknownFields == null) { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - unknownFields.MergeVarintField(2, (ulong)(int)unknown); - } - break; - } - } - } - - if (unknownFields != null) { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - - - public bool HasNumber { - get { return result.hasNumber; } - } - public string Number { - get { return result.Number; } - set { SetNumber(value); } - } - public Builder SetNumber(string value) { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.hasNumber = true; - result.number_ = value; - return this; - } - public Builder ClearNumber() { - PrepareBuilder(); - result.hasNumber = false; - result.number_ = ""; - return this; - } - - public bool HasType { - get { return result.hasType; } - } - public global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType Type { - get { return result.Type; } - set { SetType(value); } - } - public Builder SetType(global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType value) { - PrepareBuilder(); - result.hasType = true; - result.type_ = value; - return this; - } - public Builder ClearType() { - PrepareBuilder(); - result.hasType = false; - result.type_ = global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneType.HOME; - return this; - } - } - static PhoneNumber() { - object.ReferenceEquals(global::Google.ProtocolBuffers.Examples.AddressBook.Addressbook.Descriptor, null); - } - } + public Person(Person other) : this() { + name_ = other.name_; + id_ = other.id_; + email_ = other.email_; + phones_ = other.phones_.Clone(); + } + public Person Clone() { + return new Person(this); } - #endregion public const int NameFieldNumber = 1; - private bool hasName; private string name_ = ""; - public bool HasName { - get { return hasName; } - } public string Name { get { return name_; } + set { + name_ = pb::Preconditions.CheckNotNull(value, "value"); + } } public const int IdFieldNumber = 2; - private bool hasId; private int id_; - public bool HasId { - get { return hasId; } - } public int Id { get { return id_; } + set { + id_ = value; + } } public const int EmailFieldNumber = 3; - private bool hasEmail; private string email_ = ""; - public bool HasEmail { - get { return hasEmail; } - } public string Email { get { return email_; } + set { + email_ = pb::Preconditions.CheckNotNull(value, "value"); + } } - public const int PhoneFieldNumber = 4; - private pbc::PopsicleList phone_ = new pbc::PopsicleList(); - public scg::IList PhoneList { - get { return phone_; } - } - public int PhoneCount { - get { return phone_.Count; } + public const int PhonesFieldNumber = 4; + private static readonly pb::FieldCodec _repeated_phones_codec + = pb::FieldCodec.ForMessage(34, global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneNumber.Parser); + private readonly pbc::RepeatedField phones_ = new pbc::RepeatedField(); + public pbc::RepeatedField Phones { + get { return phones_; } } - public global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber GetPhone(int index) { - return phone_[index]; + + public override bool Equals(object other) { + return Equals(other as Person); } - public override bool IsInitialized { - get { - if (!hasName) return false; - if (!hasId) return false; - foreach (global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber element in PhoneList) { - if (!element.IsInitialized) return false; - } + public bool Equals(Person other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { return true; } + if (Name != other.Name) return false; + if (Id != other.Id) return false; + if (Email != other.Email) return false; + if(!phones_.Equals(other.phones_)) return false; + return true; } - public override void WriteTo(pb::ICodedOutputStream output) { - CalcSerializedSize(); - string[] field_names = _personFieldNames; - if (hasName) { - output.WriteString(1, field_names[2], Name); - } - if (hasId) { - output.WriteInt32(2, field_names[1], Id); + public override int GetHashCode() { + int hash = 1; + if (Name.Length != 0) hash ^= Name.GetHashCode(); + if (Id != 0) hash ^= Id.GetHashCode(); + if (Email.Length != 0) hash ^= Email.GetHashCode(); + hash ^= phones_.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (Name.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Name); } - if (hasEmail) { - output.WriteString(3, field_names[0], Email); + if (Id != 0) { + output.WriteRawTag(16); + output.WriteInt32(Id); } - if (phone_.Count > 0) { - output.WriteMessageArray(4, field_names[3], phone_); + if (Email.Length != 0) { + output.WriteRawTag(26); + output.WriteString(Email); } - UnknownFields.WriteTo(output); + phones_.WriteTo(output, _repeated_phones_codec); } - private int memoizedSerializedSize = -1; - public override int SerializedSize { - get { - int size = memoizedSerializedSize; - if (size != -1) return size; - return CalcSerializedSize(); + public int CalculateSize() { + int size = 0; + if (Name.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); + } + if (Id != 0) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Id); + } + if (Email.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Email); } + size += phones_.CalculateSize(_repeated_phones_codec); + return size; } - private int CalcSerializedSize() { - int size = memoizedSerializedSize; - if (size != -1) return size; - - size = 0; - if (hasName) { - size += pb::CodedOutputStream.ComputeStringSize(1, Name); + public void MergeFrom(Person other) { + if (other == null) { + return; } - if (hasId) { - size += pb::CodedOutputStream.ComputeInt32Size(2, Id); + if (other.Name.Length != 0) { + Name = other.Name; } - if (hasEmail) { - size += pb::CodedOutputStream.ComputeStringSize(3, Email); + if (other.Id != 0) { + Id = other.Id; } - foreach (global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber element in PhoneList) { - size += pb::CodedOutputStream.ComputeMessageSize(4, element); + if (other.Email.Length != 0) { + Email = other.Email; } - size += UnknownFields.SerializedSize; - memoizedSerializedSize = size; - return size; - } - public static Person ParseFrom(pb::ByteString data) { - return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static Person ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { - return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static Person ParseFrom(byte[] data) { - return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static Person ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { - return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static Person ParseFrom(global::System.IO.Stream input) { - return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static Person ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { - return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - public static Person ParseDelimitedFrom(global::System.IO.Stream input) { - return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); - } - public static Person ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { - return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); - } - public static Person ParseFrom(pb::ICodedInputStream input) { - return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static Person ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { - return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - private Person MakeReadOnly() { - phone_.MakeReadOnly(); - return this; + phones_.Add(other.phones_); } - public static Builder CreateBuilder() { return new Builder(); } - public override Builder ToBuilder() { return CreateBuilder(this); } - public override Builder CreateBuilderForType() { return new Builder(); } - public static Builder CreateBuilder(Person prototype) { - return new Builder(prototype); + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 10: { + Name = input.ReadString(); + break; + } + case 16: { + Id = input.ReadInt32(); + break; + } + case 26: { + Email = input.ReadString(); + break; + } + case 34: { + phones_.AddEntriesFrom(input, _repeated_phones_codec); + break; + } + } + } } + #region Nested types [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class Builder : pb::GeneratedBuilder { - protected override Builder ThisBuilder { - get { return this; } - } - public Builder() { - result = DefaultInstance; - resultIsReadOnly = true; - } - internal Builder(Person cloneFrom) { - result = cloneFrom; - resultIsReadOnly = true; + public static partial class Types { + public enum PhoneType { + MOBILE = 0, + HOME = 1, + WORK = 2, } - private bool resultIsReadOnly; - private Person result; + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public sealed partial class PhoneNumber : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new PhoneNumber()); + public static pb::MessageParser Parser { get { return _parser; } } - private Person PrepareBuilder() { - if (resultIsReadOnly) { - Person original = result; - result = new Person(); - resultIsReadOnly = false; - MergeFrom(original); + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Examples.AddressBook.Person.Descriptor.NestedTypes[0]; } } - return result; - } - public override bool IsInitialized { - get { return result.IsInitialized; } - } + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } - protected override Person MessageBeingBuilt { - get { return PrepareBuilder(); } - } + public PhoneNumber() { + OnConstruction(); + } - public override Builder Clear() { - result = DefaultInstance; - resultIsReadOnly = true; - return this; - } + partial void OnConstruction(); - public override Builder Clone() { - if (resultIsReadOnly) { - return new Builder(result); - } else { - return new Builder().MergeFrom(result); + public PhoneNumber(PhoneNumber other) : this() { + number_ = other.number_; + type_ = other.type_; } - } - public override pbd::MessageDescriptor DescriptorForType { - get { return global::Google.ProtocolBuffers.Examples.AddressBook.Person.Descriptor; } - } + public PhoneNumber Clone() { + return new PhoneNumber(this); + } - public override Person DefaultInstanceForType { - get { return global::Google.ProtocolBuffers.Examples.AddressBook.Person.DefaultInstance; } - } + public const int NumberFieldNumber = 1; + private string number_ = ""; + public string Number { + get { return number_; } + set { + number_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } - public override Person BuildPartial() { - if (resultIsReadOnly) { - return result; + public const int TypeFieldNumber = 2; + private global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneType type_ = global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneType.MOBILE; + public global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneType Type { + get { return type_; } + set { + type_ = value; + } } - resultIsReadOnly = true; - return result.MakeReadOnly(); - } - public override Builder MergeFrom(pb::IMessage other) { - if (other is Person) { - return MergeFrom((Person) other); - } else { - base.MergeFrom(other); - return this; + public override bool Equals(object other) { + return Equals(other as PhoneNumber); } - } - public override Builder MergeFrom(Person other) { - if (other == global::Google.ProtocolBuffers.Examples.AddressBook.Person.DefaultInstance) return this; - PrepareBuilder(); - if (other.HasName) { - Name = other.Name; + public bool Equals(PhoneNumber other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Number != other.Number) return false; + if (Type != other.Type) return false; + return true; } - if (other.HasId) { - Id = other.Id; + + public override int GetHashCode() { + int hash = 1; + if (Number.Length != 0) hash ^= Number.GetHashCode(); + if (Type != global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneType.MOBILE) hash ^= Type.GetHashCode(); + return hash; } - if (other.HasEmail) { - Email = other.Email; + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); } - if (other.phone_.Count != 0) { - result.phone_.Add(other.phone_); + + public void WriteTo(pb::CodedOutputStream output) { + if (Number.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Number); + } + if (Type != global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneType.MOBILE) { + output.WriteRawTag(16); + output.WriteEnum((int) Type); + } } - this.MergeUnknownFields(other.UnknownFields); - return this; - } - public override Builder MergeFrom(pb::ICodedInputStream input) { - return MergeFrom(input, pb::ExtensionRegistry.Empty); - } + public int CalculateSize() { + int size = 0; + if (Number.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Number); + } + if (Type != global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneType.MOBILE) { + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type); + } + return size; + } - public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { - PrepareBuilder(); - pb::UnknownFieldSet.Builder unknownFields = null; - uint tag; - string field_name; - while (input.ReadTag(out tag, out field_name)) { - if(tag == 0 && field_name != null) { - int field_ordinal = global::System.Array.BinarySearch(_personFieldNames, field_name, global::System.StringComparer.Ordinal); - if(field_ordinal >= 0) - tag = _personFieldTags[field_ordinal]; - else { - if (unknownFields == null) { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - continue; - } + public void MergeFrom(PhoneNumber other) { + if (other == null) { + return; } - switch (tag) { - case 0: { - throw pb::InvalidProtocolBufferException.InvalidTag(); - } - default: { - if (pb::WireFormat.IsEndGroupTag(tag)) { - if (unknownFields != null) { - this.UnknownFields = unknownFields.Build(); - } - return this; + if (other.Number.Length != 0) { + Number = other.Number; + } + if (other.Type != global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneType.MOBILE) { + Type = other.Type; + } + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 10: { + Number = input.ReadString(); + break; } - if (unknownFields == null) { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); + case 16: { + type_ = (global::Google.Protobuf.Examples.AddressBook.Person.Types.PhoneType) input.ReadEnum(); + break; } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - break; - } - case 10: { - result.hasName = input.ReadString(ref result.name_); - break; - } - case 16: { - result.hasId = input.ReadInt32(ref result.id_); - break; - } - case 26: { - result.hasEmail = input.ReadString(ref result.email_); - break; - } - case 34: { - input.ReadMessageArray(tag, field_name, result.phone_, global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.DefaultInstance, extensionRegistry); - break; } } } - if (unknownFields != null) { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - - - public bool HasName { - get { return result.hasName; } - } - public string Name { - get { return result.Name; } - set { SetName(value); } - } - public Builder SetName(string value) { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.hasName = true; - result.name_ = value; - return this; - } - public Builder ClearName() { - PrepareBuilder(); - result.hasName = false; - result.name_ = ""; - return this; - } - - public bool HasId { - get { return result.hasId; } - } - public int Id { - get { return result.Id; } - set { SetId(value); } - } - public Builder SetId(int value) { - PrepareBuilder(); - result.hasId = true; - result.id_ = value; - return this; - } - public Builder ClearId() { - PrepareBuilder(); - result.hasId = false; - result.id_ = 0; - return this; - } - - public bool HasEmail { - get { return result.hasEmail; } - } - public string Email { - get { return result.Email; } - set { SetEmail(value); } - } - public Builder SetEmail(string value) { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.hasEmail = true; - result.email_ = value; - return this; - } - public Builder ClearEmail() { - PrepareBuilder(); - result.hasEmail = false; - result.email_ = ""; - return this; } - public pbc::IPopsicleList PhoneList { - get { return PrepareBuilder().phone_; } - } - public int PhoneCount { - get { return result.PhoneCount; } - } - public global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber GetPhone(int index) { - return result.GetPhone(index); - } - public Builder SetPhone(int index, global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber value) { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.phone_[index] = value; - return this; - } - public Builder SetPhone(int index, global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.Builder builderForValue) { - pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); - PrepareBuilder(); - result.phone_[index] = builderForValue.Build(); - return this; - } - public Builder AddPhone(global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber value) { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.phone_.Add(value); - return this; - } - public Builder AddPhone(global::Google.ProtocolBuffers.Examples.AddressBook.Person.Types.PhoneNumber.Builder builderForValue) { - pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); - PrepareBuilder(); - result.phone_.Add(builderForValue.Build()); - return this; - } - public Builder AddRangePhone(scg::IEnumerable values) { - PrepareBuilder(); - result.phone_.Add(values); - return this; - } - public Builder ClearPhone() { - PrepareBuilder(); - result.phone_.Clear(); - return this; - } - } - static Person() { - object.ReferenceEquals(global::Google.ProtocolBuffers.Examples.AddressBook.Addressbook.Descriptor, null); } + #endregion + } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class AddressBook : pb::GeneratedMessage { - private AddressBook() { } - private static readonly AddressBook defaultInstance = new AddressBook().MakeReadOnly(); - private static readonly string[] _addressBookFieldNames = new string[] { "person" }; - private static readonly uint[] _addressBookFieldTags = new uint[] { 10 }; - public static AddressBook DefaultInstance { - get { return defaultInstance; } - } + public sealed partial class AddressBook : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new AddressBook()); + public static pb::MessageParser Parser { get { return _parser; } } - public override AddressBook DefaultInstanceForType { - get { return DefaultInstance; } + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Examples.AddressBook.Addressbook.Descriptor.MessageTypes[1]; } } - protected override AddressBook ThisMessage { - get { return this; } + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } } - public static pbd::MessageDescriptor Descriptor { - get { return global::Google.ProtocolBuffers.Examples.AddressBook.Addressbook.internal__static_tutorial_AddressBook__Descriptor; } + public AddressBook() { + OnConstruction(); } - protected override pb::FieldAccess.FieldAccessorTable InternalFieldAccessors { - get { return global::Google.ProtocolBuffers.Examples.AddressBook.Addressbook.internal__static_tutorial_AddressBook__FieldAccessorTable; } + partial void OnConstruction(); + + public AddressBook(AddressBook other) : this() { + people_ = other.people_.Clone(); } - public const int PersonFieldNumber = 1; - private pbc::PopsicleList person_ = new pbc::PopsicleList(); - public scg::IList PersonList { - get { return person_; } + public AddressBook Clone() { + return new AddressBook(this); } - public int PersonCount { - get { return person_.Count; } + + public const int PeopleFieldNumber = 1; + private static readonly pb::FieldCodec _repeated_people_codec + = pb::FieldCodec.ForMessage(10, global::Google.Protobuf.Examples.AddressBook.Person.Parser); + private readonly pbc::RepeatedField people_ = new pbc::RepeatedField(); + public pbc::RepeatedField People { + get { return people_; } } - public global::Google.ProtocolBuffers.Examples.AddressBook.Person GetPerson(int index) { - return person_[index]; + + public override bool Equals(object other) { + return Equals(other as AddressBook); } - public override bool IsInitialized { - get { - foreach (global::Google.ProtocolBuffers.Examples.AddressBook.Person element in PersonList) { - if (!element.IsInitialized) return false; - } + public bool Equals(AddressBook other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { return true; } + if(!people_.Equals(other.people_)) return false; + return true; } - public override void WriteTo(pb::ICodedOutputStream output) { - CalcSerializedSize(); - string[] field_names = _addressBookFieldNames; - if (person_.Count > 0) { - output.WriteMessageArray(1, field_names[0], person_); - } - UnknownFields.WriteTo(output); + public override int GetHashCode() { + int hash = 1; + hash ^= people_.GetHashCode(); + return hash; } - private int memoizedSerializedSize = -1; - public override int SerializedSize { - get { - int size = memoizedSerializedSize; - if (size != -1) return size; - return CalcSerializedSize(); - } + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); } - private int CalcSerializedSize() { - int size = memoizedSerializedSize; - if (size != -1) return size; - - size = 0; - foreach (global::Google.ProtocolBuffers.Examples.AddressBook.Person element in PersonList) { - size += pb::CodedOutputStream.ComputeMessageSize(1, element); - } - size += UnknownFields.SerializedSize; - memoizedSerializedSize = size; - return size; - } - public static AddressBook ParseFrom(pb::ByteString data) { - return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static AddressBook ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { - return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static AddressBook ParseFrom(byte[] data) { - return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); - } - public static AddressBook ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { - return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); - } - public static AddressBook ParseFrom(global::System.IO.Stream input) { - return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static AddressBook ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { - return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - public static AddressBook ParseDelimitedFrom(global::System.IO.Stream input) { - return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); - } - public static AddressBook ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { - return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); - } - public static AddressBook ParseFrom(pb::ICodedInputStream input) { - return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); - } - public static AddressBook ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { - return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); - } - private AddressBook MakeReadOnly() { - person_.MakeReadOnly(); - return this; + public void WriteTo(pb::CodedOutputStream output) { + people_.WriteTo(output, _repeated_people_codec); } - public static Builder CreateBuilder() { return new Builder(); } - public override Builder ToBuilder() { return CreateBuilder(this); } - public override Builder CreateBuilderForType() { return new Builder(); } - public static Builder CreateBuilder(AddressBook prototype) { - return new Builder(prototype); + public int CalculateSize() { + int size = 0; + size += people_.CalculateSize(_repeated_people_codec); + return size; } - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - public sealed partial class Builder : pb::GeneratedBuilder { - protected override Builder ThisBuilder { - get { return this; } - } - public Builder() { - result = DefaultInstance; - resultIsReadOnly = true; - } - internal Builder(AddressBook cloneFrom) { - result = cloneFrom; - resultIsReadOnly = true; - } - - private bool resultIsReadOnly; - private AddressBook result; - - private AddressBook PrepareBuilder() { - if (resultIsReadOnly) { - AddressBook original = result; - result = new AddressBook(); - resultIsReadOnly = false; - MergeFrom(original); - } - return result; - } - - public override bool IsInitialized { - get { return result.IsInitialized; } - } - - protected override AddressBook MessageBeingBuilt { - get { return PrepareBuilder(); } - } - - public override Builder Clear() { - result = DefaultInstance; - resultIsReadOnly = true; - return this; - } - - public override Builder Clone() { - if (resultIsReadOnly) { - return new Builder(result); - } else { - return new Builder().MergeFrom(result); - } - } - - public override pbd::MessageDescriptor DescriptorForType { - get { return global::Google.ProtocolBuffers.Examples.AddressBook.AddressBook.Descriptor; } - } - - public override AddressBook DefaultInstanceForType { - get { return global::Google.ProtocolBuffers.Examples.AddressBook.AddressBook.DefaultInstance; } - } - - public override AddressBook BuildPartial() { - if (resultIsReadOnly) { - return result; - } - resultIsReadOnly = true; - return result.MakeReadOnly(); - } - - public override Builder MergeFrom(pb::IMessage other) { - if (other is AddressBook) { - return MergeFrom((AddressBook) other); - } else { - base.MergeFrom(other); - return this; - } - } - - public override Builder MergeFrom(AddressBook other) { - if (other == global::Google.ProtocolBuffers.Examples.AddressBook.AddressBook.DefaultInstance) return this; - PrepareBuilder(); - if (other.person_.Count != 0) { - result.person_.Add(other.person_); - } - this.MergeUnknownFields(other.UnknownFields); - return this; - } - - public override Builder MergeFrom(pb::ICodedInputStream input) { - return MergeFrom(input, pb::ExtensionRegistry.Empty); + public void MergeFrom(AddressBook other) { + if (other == null) { + return; } + people_.Add(other.people_); + } - public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { - PrepareBuilder(); - pb::UnknownFieldSet.Builder unknownFields = null; - uint tag; - string field_name; - while (input.ReadTag(out tag, out field_name)) { - if(tag == 0 && field_name != null) { - int field_ordinal = global::System.Array.BinarySearch(_addressBookFieldNames, field_name, global::System.StringComparer.Ordinal); - if(field_ordinal >= 0) - tag = _addressBookFieldTags[field_ordinal]; - else { - if (unknownFields == null) { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - continue; - } - } - switch (tag) { - case 0: { - throw pb::InvalidProtocolBufferException.InvalidTag(); - } - default: { - if (pb::WireFormat.IsEndGroupTag(tag)) { - if (unknownFields != null) { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - if (unknownFields == null) { - unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); - } - ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); - break; - } - case 10: { - input.ReadMessageArray(tag, field_name, result.person_, global::Google.ProtocolBuffers.Examples.AddressBook.Person.DefaultInstance, extensionRegistry); - break; - } + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 10: { + people_.AddEntriesFrom(input, _repeated_people_codec); + break; } } - - if (unknownFields != null) { - this.UnknownFields = unknownFields.Build(); - } - return this; - } - - - public pbc::IPopsicleList PersonList { - get { return PrepareBuilder().person_; } - } - public int PersonCount { - get { return result.PersonCount; } - } - public global::Google.ProtocolBuffers.Examples.AddressBook.Person GetPerson(int index) { - return result.GetPerson(index); - } - public Builder SetPerson(int index, global::Google.ProtocolBuffers.Examples.AddressBook.Person value) { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.person_[index] = value; - return this; - } - public Builder SetPerson(int index, global::Google.ProtocolBuffers.Examples.AddressBook.Person.Builder builderForValue) { - pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); - PrepareBuilder(); - result.person_[index] = builderForValue.Build(); - return this; - } - public Builder AddPerson(global::Google.ProtocolBuffers.Examples.AddressBook.Person value) { - pb::ThrowHelper.ThrowIfNull(value, "value"); - PrepareBuilder(); - result.person_.Add(value); - return this; - } - public Builder AddPerson(global::Google.ProtocolBuffers.Examples.AddressBook.Person.Builder builderForValue) { - pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); - PrepareBuilder(); - result.person_.Add(builderForValue.Build()); - return this; - } - public Builder AddRangePerson(scg::IEnumerable values) { - PrepareBuilder(); - result.person_.Add(values); - return this; - } - public Builder ClearPerson() { - PrepareBuilder(); - result.person_.Clear(); - return this; } } - static AddressBook() { - object.ReferenceEquals(global::Google.ProtocolBuffers.Examples.AddressBook.Addressbook.Descriptor, null); - } + } #endregion diff --git a/csharp/src/AddressBook/ListPeople.cs b/csharp/src/AddressBook/ListPeople.cs index fe6f52d82870d..3979430fe21d5 100644 --- a/csharp/src/AddressBook/ListPeople.cs +++ b/csharp/src/AddressBook/ListPeople.cs @@ -1,10 +1,7 @@ #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/ +// 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 @@ -31,13 +28,12 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - #endregion using System; using System.IO; -namespace Google.ProtocolBuffers.Examples.AddressBook +namespace Google.Protobuf.Examples.AddressBook { internal class ListPeople { @@ -46,16 +42,16 @@ internal class ListPeople /// private static void Print(AddressBook addressBook) { - foreach (Person person in addressBook.PersonList) + foreach (Person person in addressBook.People) { Console.WriteLine("Person ID: {0}", person.Id); Console.WriteLine(" Name: {0}", person.Name); - if (person.HasEmail) + if (person.Email != "") { Console.WriteLine(" E-mail address: {0}", person.Email); } - foreach (Person.Types.PhoneNumber phoneNumber in person.PhoneList) + foreach (Person.Types.PhoneNumber phoneNumber in person.Phones) { switch (phoneNumber.Type) { @@ -94,7 +90,7 @@ public static int Main(string[] args) // Read the existing address book. using (Stream stream = File.OpenRead(args[0])) { - AddressBook addressBook = AddressBook.ParseFrom(stream); + AddressBook addressBook = AddressBook.Parser.ParseFrom(stream); Print(addressBook); } return 0; diff --git a/csharp/src/AddressBook/Program.cs b/csharp/src/AddressBook/Program.cs index e0d6d49bb9923..ff7b9c085e072 100644 --- a/csharp/src/AddressBook/Program.cs +++ b/csharp/src/AddressBook/Program.cs @@ -1,10 +1,7 @@ #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/ +// 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 @@ -31,12 +28,11 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - #endregion using System; -namespace Google.ProtocolBuffers.Examples.AddressBook +namespace Google.Protobuf.Examples.AddressBook { /// /// Entry point. Repeatedly prompts user for an action to take, delegating actual behaviour diff --git a/csharp/src/AddressBook/Properties/AssemblyInfo.cs b/csharp/src/AddressBook/Properties/AssemblyInfo.cs index e9c40dce11958..9cb014c0d7f7f 100644 --- a/csharp/src/AddressBook/Properties/AssemblyInfo.cs +++ b/csharp/src/AddressBook/Properties/AssemblyInfo.cs @@ -10,20 +10,9 @@ [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AddressBook")] -[assembly: AssemblyCopyright("Copyright © 2008")] +[assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("2.4.1.555")] - -[assembly: AssemblyVersion("2.4.1.555")] -[assembly: AssemblyFileVersion("2.4.1.555")] \ No newline at end of file +[assembly: AssemblyVersion("3.0.0.0")] +[assembly: AssemblyFileVersion("3.0.0.0")] diff --git a/csharp/src/AddressBook/SampleUsage.cs b/csharp/src/AddressBook/SampleUsage.cs index 084b16558ebee..936c3bea68765 100644 --- a/csharp/src/AddressBook/SampleUsage.cs +++ b/csharp/src/AddressBook/SampleUsage.cs @@ -1,44 +1,70 @@ -using System; +#region Copyright notice and license +// 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. +#endregion + +using System; using System.IO; -namespace Google.ProtocolBuffers.Examples.AddressBook +namespace Google.Protobuf.Examples.AddressBook { internal class SampleUsage { private static void Main() { byte[] bytes; - //Create a builder to start building a message - Person.Builder newContact = Person.CreateBuilder(); - //Set the primitive properties - newContact.SetId(1) - .SetName("Foo") - .SetEmail("foo@bar"); - //Now add an item to a list (repeating) field - newContact.AddPhone( - //Create the child message inline - Person.Types.PhoneNumber.CreateBuilder().SetNumber("555-1212").Build() - ); - //Now build the final message: - Person person = newContact.Build(); - //The builder is no longer valid (at least not now, scheduled for 2.4): - newContact = null; + // Create a new person + Person person = new Person + { + Id = 1, + Name = "Foo", + Email = "foo@bar", + Phones = { new Person.Types.PhoneNumber { Number = "555-1212" } } + }; using (MemoryStream stream = new MemoryStream()) { - //Save the person to a stream + // Save the person to a stream person.WriteTo(stream); bytes = stream.ToArray(); } - //Create another builder, merge the byte[], and build the message: - Person copy = Person.CreateBuilder().MergeFrom(bytes).Build(); + Person copy = Person.Parser.ParseFrom(bytes); - //A more streamlined approach might look like this: - bytes = AddressBook.CreateBuilder().AddPerson(copy).Build().ToByteArray(); - //And read the address book back again - AddressBook restored = AddressBook.CreateBuilder().MergeFrom(bytes).Build(); - //The message performs a deep-comparison on equality: - if (restored.PersonCount != 1 || !person.Equals(restored.PersonList[0])) + // A more streamlined approach might look like this: + bytes = copy.ToByteArray(); + // And read the address book back again + AddressBook restored = AddressBook.Parser.ParseFrom(bytes); + // The message performs a deep-comparison on equality: + if (restored.People.Count != 1 || !person.Equals(restored.People[0])) + { throw new ApplicationException("There is a bad person in here!"); + } } } } \ No newline at end of file diff --git a/csharp/src/AddressBook/app.config b/csharp/src/AddressBook/app.config index 19fac17a81431..a80813afe3fec 100644 --- a/csharp/src/AddressBook/app.config +++ b/csharp/src/AddressBook/app.config @@ -1,3 +1,3 @@ - + diff --git a/csharp/src/Google.Protobuf.Conformance/App.config b/csharp/src/Google.Protobuf.Conformance/App.config new file mode 100644 index 0000000000000..8e15646352ec1 --- /dev/null +++ b/csharp/src/Google.Protobuf.Conformance/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/csharp/src/Google.Protobuf.Conformance/Conformance.cs b/csharp/src/Google.Protobuf.Conformance/Conformance.cs new file mode 100644 index 0000000000000..e905d4e4e1120 --- /dev/null +++ b/csharp/src/Google.Protobuf.Conformance/Conformance.cs @@ -0,0 +1,2380 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: conformance.proto +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace Conformance { + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public static partial class Conformance { + + #region Descriptor + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static Conformance() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "ChFjb25mb3JtYW5jZS5wcm90bxILY29uZm9ybWFuY2UijQEKEkNvbmZvcm1h", + "bmNlUmVxdWVzdBIaChBwcm90b2J1Zl9wYXlsb2FkGAEgASgMSAASFgoManNv", + "bl9wYXlsb2FkGAIgASgJSAASOAoXcmVxdWVzdGVkX291dHB1dF9mb3JtYXQY", + "AyABKA4yFy5jb25mb3JtYW5jZS5XaXJlRm9ybWF0QgkKB3BheWxvYWQilgEK", + "E0NvbmZvcm1hbmNlUmVzcG9uc2USFQoLcGFyc2VfZXJyb3IYASABKAlIABIX", + "Cg1ydW50aW1lX2Vycm9yGAIgASgJSAASGgoQcHJvdG9idWZfcGF5bG9hZBgD", + "IAEoDEgAEhYKDGpzb25fcGF5bG9hZBgEIAEoCUgAEhEKB3NraXBwZWQYBSAB", + "KAlIAEIICgZyZXN1bHQi6yIKDFRlc3RBbGxUeXBlcxIWCg5vcHRpb25hbF9p", + "bnQzMhgBIAEoBRIWCg5vcHRpb25hbF9pbnQ2NBgCIAEoAxIXCg9vcHRpb25h", + "bF91aW50MzIYAyABKA0SFwoPb3B0aW9uYWxfdWludDY0GAQgASgEEhcKD29w", + "dGlvbmFsX3NpbnQzMhgFIAEoERIXCg9vcHRpb25hbF9zaW50NjQYBiABKBIS", + "GAoQb3B0aW9uYWxfZml4ZWQzMhgHIAEoBxIYChBvcHRpb25hbF9maXhlZDY0", + "GAggASgGEhkKEW9wdGlvbmFsX3NmaXhlZDMyGAkgASgPEhkKEW9wdGlvbmFs", + "X3NmaXhlZDY0GAogASgQEhYKDm9wdGlvbmFsX2Zsb2F0GAsgASgCEhcKD29w", + "dGlvbmFsX2RvdWJsZRgMIAEoARIVCg1vcHRpb25hbF9ib29sGA0gASgIEhcK", + "D29wdGlvbmFsX3N0cmluZxgOIAEoCRIWCg5vcHRpb25hbF9ieXRlcxgPIAEo", + "DBJIChdvcHRpb25hbF9uZXN0ZWRfbWVzc2FnZRgSIAEoCzInLmNvbmZvcm1h", + "bmNlLlRlc3RBbGxUeXBlcy5OZXN0ZWRNZXNzYWdlEj0KGG9wdGlvbmFsX2Zv", + "cmVpZ25fbWVzc2FnZRgTIAEoCzIbLmNvbmZvcm1hbmNlLkZvcmVpZ25NZXNz", + "YWdlEkIKFG9wdGlvbmFsX25lc3RlZF9lbnVtGBUgASgOMiQuY29uZm9ybWFu", + "Y2UuVGVzdEFsbFR5cGVzLk5lc3RlZEVudW0SNwoVb3B0aW9uYWxfZm9yZWln", + "bl9lbnVtGBYgASgOMhguY29uZm9ybWFuY2UuRm9yZWlnbkVudW0SIQoVb3B0", + "aW9uYWxfc3RyaW5nX3BpZWNlGBggASgJQgIIAhIZCg1vcHRpb25hbF9jb3Jk", + "GBkgASgJQgIIARI0ChFyZWN1cnNpdmVfbWVzc2FnZRgbIAEoCzIZLmNvbmZv", + "cm1hbmNlLlRlc3RBbGxUeXBlcxIWCg5yZXBlYXRlZF9pbnQzMhgfIAMoBRIW", + "Cg5yZXBlYXRlZF9pbnQ2NBggIAMoAxIXCg9yZXBlYXRlZF91aW50MzIYISAD", + "KA0SFwoPcmVwZWF0ZWRfdWludDY0GCIgAygEEhcKD3JlcGVhdGVkX3NpbnQz", + "MhgjIAMoERIXCg9yZXBlYXRlZF9zaW50NjQYJCADKBISGAoQcmVwZWF0ZWRf", + "Zml4ZWQzMhglIAMoBxIYChByZXBlYXRlZF9maXhlZDY0GCYgAygGEhkKEXJl", + "cGVhdGVkX3NmaXhlZDMyGCcgAygPEhkKEXJlcGVhdGVkX3NmaXhlZDY0GCgg", + "AygQEhYKDnJlcGVhdGVkX2Zsb2F0GCkgAygCEhcKD3JlcGVhdGVkX2RvdWJs", + "ZRgqIAMoARIVCg1yZXBlYXRlZF9ib29sGCsgAygIEhcKD3JlcGVhdGVkX3N0", + "cmluZxgsIAMoCRIWCg5yZXBlYXRlZF9ieXRlcxgtIAMoDBJIChdyZXBlYXRl", + "ZF9uZXN0ZWRfbWVzc2FnZRgwIAMoCzInLmNvbmZvcm1hbmNlLlRlc3RBbGxU", + "eXBlcy5OZXN0ZWRNZXNzYWdlEj0KGHJlcGVhdGVkX2ZvcmVpZ25fbWVzc2Fn", + "ZRgxIAMoCzIbLmNvbmZvcm1hbmNlLkZvcmVpZ25NZXNzYWdlEkIKFHJlcGVh", + "dGVkX25lc3RlZF9lbnVtGDMgAygOMiQuY29uZm9ybWFuY2UuVGVzdEFsbFR5", + "cGVzLk5lc3RlZEVudW0SNwoVcmVwZWF0ZWRfZm9yZWlnbl9lbnVtGDQgAygO", + "MhguY29uZm9ybWFuY2UuRm9yZWlnbkVudW0SIQoVcmVwZWF0ZWRfc3RyaW5n", + "X3BpZWNlGDYgAygJQgIIAhIZCg1yZXBlYXRlZF9jb3JkGDcgAygJQgIIARJF", + "Cg9tYXBfaW50MzJfaW50MzIYOCADKAsyLC5jb25mb3JtYW5jZS5UZXN0QWxs", + "VHlwZXMuTWFwSW50MzJJbnQzMkVudHJ5EkUKD21hcF9pbnQ2NF9pbnQ2NBg5", + "IAMoCzIsLmNvbmZvcm1hbmNlLlRlc3RBbGxUeXBlcy5NYXBJbnQ2NEludDY0", + "RW50cnkSSQoRbWFwX3VpbnQzMl91aW50MzIYOiADKAsyLi5jb25mb3JtYW5j", + "ZS5UZXN0QWxsVHlwZXMuTWFwVWludDMyVWludDMyRW50cnkSSQoRbWFwX3Vp", + "bnQ2NF91aW50NjQYOyADKAsyLi5jb25mb3JtYW5jZS5UZXN0QWxsVHlwZXMu", + "TWFwVWludDY0VWludDY0RW50cnkSSQoRbWFwX3NpbnQzMl9zaW50MzIYPCAD", + "KAsyLi5jb25mb3JtYW5jZS5UZXN0QWxsVHlwZXMuTWFwU2ludDMyU2ludDMy", + "RW50cnkSSQoRbWFwX3NpbnQ2NF9zaW50NjQYPSADKAsyLi5jb25mb3JtYW5j", + "ZS5UZXN0QWxsVHlwZXMuTWFwU2ludDY0U2ludDY0RW50cnkSTQoTbWFwX2Zp", + "eGVkMzJfZml4ZWQzMhg+IAMoCzIwLmNvbmZvcm1hbmNlLlRlc3RBbGxUeXBl", + "cy5NYXBGaXhlZDMyRml4ZWQzMkVudHJ5Ek0KE21hcF9maXhlZDY0X2ZpeGVk", + "NjQYPyADKAsyMC5jb25mb3JtYW5jZS5UZXN0QWxsVHlwZXMuTWFwRml4ZWQ2", + "NEZpeGVkNjRFbnRyeRJRChVtYXBfc2ZpeGVkMzJfc2ZpeGVkMzIYQCADKAsy", + "Mi5jb25mb3JtYW5jZS5UZXN0QWxsVHlwZXMuTWFwU2ZpeGVkMzJTZml4ZWQz", + "MkVudHJ5ElEKFW1hcF9zZml4ZWQ2NF9zZml4ZWQ2NBhBIAMoCzIyLmNvbmZv", + "cm1hbmNlLlRlc3RBbGxUeXBlcy5NYXBTZml4ZWQ2NFNmaXhlZDY0RW50cnkS", + "RQoPbWFwX2ludDMyX2Zsb2F0GEIgAygLMiwuY29uZm9ybWFuY2UuVGVzdEFs", + "bFR5cGVzLk1hcEludDMyRmxvYXRFbnRyeRJHChBtYXBfaW50MzJfZG91Ymxl", + "GEMgAygLMi0uY29uZm9ybWFuY2UuVGVzdEFsbFR5cGVzLk1hcEludDMyRG91", + "YmxlRW50cnkSQQoNbWFwX2Jvb2xfYm9vbBhEIAMoCzIqLmNvbmZvcm1hbmNl", + "LlRlc3RBbGxUeXBlcy5NYXBCb29sQm9vbEVudHJ5EkkKEW1hcF9zdHJpbmdf", + "c3RyaW5nGEUgAygLMi4uY29uZm9ybWFuY2UuVGVzdEFsbFR5cGVzLk1hcFN0", + "cmluZ1N0cmluZ0VudHJ5EkcKEG1hcF9zdHJpbmdfYnl0ZXMYRiADKAsyLS5j", + "b25mb3JtYW5jZS5UZXN0QWxsVHlwZXMuTWFwU3RyaW5nQnl0ZXNFbnRyeRJY", + "ChltYXBfc3RyaW5nX25lc3RlZF9tZXNzYWdlGEcgAygLMjUuY29uZm9ybWFu", + "Y2UuVGVzdEFsbFR5cGVzLk1hcFN0cmluZ05lc3RlZE1lc3NhZ2VFbnRyeRJa", + "ChptYXBfc3RyaW5nX2ZvcmVpZ25fbWVzc2FnZRhIIAMoCzI2LmNvbmZvcm1h", + "bmNlLlRlc3RBbGxUeXBlcy5NYXBTdHJpbmdGb3JlaWduTWVzc2FnZUVudHJ5", + "ElIKFm1hcF9zdHJpbmdfbmVzdGVkX2VudW0YSSADKAsyMi5jb25mb3JtYW5j", + "ZS5UZXN0QWxsVHlwZXMuTWFwU3RyaW5nTmVzdGVkRW51bUVudHJ5ElQKF21h", + "cF9zdHJpbmdfZm9yZWlnbl9lbnVtGEogAygLMjMuY29uZm9ybWFuY2UuVGVz", + "dEFsbFR5cGVzLk1hcFN0cmluZ0ZvcmVpZ25FbnVtRW50cnkSFgoMb25lb2Zf", + "dWludDMyGG8gASgNSAASRwoUb25lb2ZfbmVzdGVkX21lc3NhZ2UYcCABKAsy", + "Jy5jb25mb3JtYW5jZS5UZXN0QWxsVHlwZXMuTmVzdGVkTWVzc2FnZUgAEhYK", + "DG9uZW9mX3N0cmluZxhxIAEoCUgAEhUKC29uZW9mX2J5dGVzGHIgASgMSAAa", + "SgoNTmVzdGVkTWVzc2FnZRIJCgFhGAEgASgFEi4KC2NvcmVjdXJzaXZlGAIg", + "ASgLMhkuY29uZm9ybWFuY2UuVGVzdEFsbFR5cGVzGjQKEk1hcEludDMySW50", + "MzJFbnRyeRILCgNrZXkYASABKAUSDQoFdmFsdWUYAiABKAU6AjgBGjQKEk1h", + "cEludDY0SW50NjRFbnRyeRILCgNrZXkYASABKAMSDQoFdmFsdWUYAiABKAM6", + "AjgBGjYKFE1hcFVpbnQzMlVpbnQzMkVudHJ5EgsKA2tleRgBIAEoDRINCgV2", + "YWx1ZRgCIAEoDToCOAEaNgoUTWFwVWludDY0VWludDY0RW50cnkSCwoDa2V5", + "GAEgASgEEg0KBXZhbHVlGAIgASgEOgI4ARo2ChRNYXBTaW50MzJTaW50MzJF", + "bnRyeRILCgNrZXkYASABKBESDQoFdmFsdWUYAiABKBE6AjgBGjYKFE1hcFNp", + "bnQ2NFNpbnQ2NEVudHJ5EgsKA2tleRgBIAEoEhINCgV2YWx1ZRgCIAEoEjoC", + "OAEaOAoWTWFwRml4ZWQzMkZpeGVkMzJFbnRyeRILCgNrZXkYASABKAcSDQoF", + "dmFsdWUYAiABKAc6AjgBGjgKFk1hcEZpeGVkNjRGaXhlZDY0RW50cnkSCwoD", + "a2V5GAEgASgGEg0KBXZhbHVlGAIgASgGOgI4ARo6ChhNYXBTZml4ZWQzMlNm", + "aXhlZDMyRW50cnkSCwoDa2V5GAEgASgPEg0KBXZhbHVlGAIgASgPOgI4ARo6", + "ChhNYXBTZml4ZWQ2NFNmaXhlZDY0RW50cnkSCwoDa2V5GAEgASgQEg0KBXZh", + "bHVlGAIgASgQOgI4ARo0ChJNYXBJbnQzMkZsb2F0RW50cnkSCwoDa2V5GAEg", + "ASgFEg0KBXZhbHVlGAIgASgCOgI4ARo1ChNNYXBJbnQzMkRvdWJsZUVudHJ5", + "EgsKA2tleRgBIAEoBRINCgV2YWx1ZRgCIAEoAToCOAEaMgoQTWFwQm9vbEJv", + "b2xFbnRyeRILCgNrZXkYASABKAgSDQoFdmFsdWUYAiABKAg6AjgBGjYKFE1h", + "cFN0cmluZ1N0cmluZ0VudHJ5EgsKA2tleRgBIAEoCRINCgV2YWx1ZRgCIAEo", + "CToCOAEaNQoTTWFwU3RyaW5nQnl0ZXNFbnRyeRILCgNrZXkYASABKAkSDQoF", + "dmFsdWUYAiABKAw6AjgBGmYKG01hcFN0cmluZ05lc3RlZE1lc3NhZ2VFbnRy", + "eRILCgNrZXkYASABKAkSNgoFdmFsdWUYAiABKAsyJy5jb25mb3JtYW5jZS5U", + "ZXN0QWxsVHlwZXMuTmVzdGVkTWVzc2FnZToCOAEaWwocTWFwU3RyaW5nRm9y", + "ZWlnbk1lc3NhZ2VFbnRyeRILCgNrZXkYASABKAkSKgoFdmFsdWUYAiABKAsy", + "Gy5jb25mb3JtYW5jZS5Gb3JlaWduTWVzc2FnZToCOAEaYAoYTWFwU3RyaW5n", + "TmVzdGVkRW51bUVudHJ5EgsKA2tleRgBIAEoCRIzCgV2YWx1ZRgCIAEoDjIk", + "LmNvbmZvcm1hbmNlLlRlc3RBbGxUeXBlcy5OZXN0ZWRFbnVtOgI4ARpVChlN", + "YXBTdHJpbmdGb3JlaWduRW51bUVudHJ5EgsKA2tleRgBIAEoCRInCgV2YWx1", + "ZRgCIAEoDjIYLmNvbmZvcm1hbmNlLkZvcmVpZ25FbnVtOgI4ASI5CgpOZXN0", + "ZWRFbnVtEgcKA0ZPTxAAEgcKA0JBUhABEgcKA0JBWhACEhAKA05FRxD/////", + "//////8BQg0KC29uZW9mX2ZpZWxkIhsKDkZvcmVpZ25NZXNzYWdlEgkKAWMY", + "ASABKAUqNQoKV2lyZUZvcm1hdBIPCgtVTlNQRUNJRklFRBAAEgwKCFBST1RP", + "QlVGEAESCAoESlNPThACKkAKC0ZvcmVpZ25FbnVtEg8KC0ZPUkVJR05fRk9P", + "EAASDwoLRk9SRUlHTl9CQVIQARIPCgtGT1JFSUdOX0JBWhACQiEKH2NvbS5n", + "b29nbGUucHJvdG9idWYuY29uZm9ybWFuY2ViBnByb3RvMw==")); + descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedCodeInfo(new[] {typeof(global::Conformance.WireFormat), typeof(global::Conformance.ForeignEnum), }, new pbr::GeneratedCodeInfo[] { + new pbr::GeneratedCodeInfo(typeof(global::Conformance.ConformanceRequest), new[]{ "ProtobufPayload", "JsonPayload", "RequestedOutputFormat" }, new[]{ "Payload" }, null, null), + new pbr::GeneratedCodeInfo(typeof(global::Conformance.ConformanceResponse), new[]{ "ParseError", "RuntimeError", "ProtobufPayload", "JsonPayload", "Skipped" }, new[]{ "Result" }, null, null), + new pbr::GeneratedCodeInfo(typeof(global::Conformance.TestAllTypes), new[]{ "OptionalInt32", "OptionalInt64", "OptionalUint32", "OptionalUint64", "OptionalSint32", "OptionalSint64", "OptionalFixed32", "OptionalFixed64", "OptionalSfixed32", "OptionalSfixed64", "OptionalFloat", "OptionalDouble", "OptionalBool", "OptionalString", "OptionalBytes", "OptionalNestedMessage", "OptionalForeignMessage", "OptionalNestedEnum", "OptionalForeignEnum", "OptionalStringPiece", "OptionalCord", "RecursiveMessage", "RepeatedInt32", "RepeatedInt64", "RepeatedUint32", "RepeatedUint64", "RepeatedSint32", "RepeatedSint64", "RepeatedFixed32", "RepeatedFixed64", "RepeatedSfixed32", "RepeatedSfixed64", "RepeatedFloat", "RepeatedDouble", "RepeatedBool", "RepeatedString", "RepeatedBytes", "RepeatedNestedMessage", "RepeatedForeignMessage", "RepeatedNestedEnum", "RepeatedForeignEnum", "RepeatedStringPiece", "RepeatedCord", "MapInt32Int32", "MapInt64Int64", "MapUint32Uint32", "MapUint64Uint64", "MapSint32Sint32", "MapSint64Sint64", "MapFixed32Fixed32", "MapFixed64Fixed64", "MapSfixed32Sfixed32", "MapSfixed64Sfixed64", "MapInt32Float", "MapInt32Double", "MapBoolBool", "MapStringString", "MapStringBytes", "MapStringNestedMessage", "MapStringForeignMessage", "MapStringNestedEnum", "MapStringForeignEnum", "OneofUint32", "OneofNestedMessage", "OneofString", "OneofBytes" }, new[]{ "OneofField" }, new[]{ typeof(global::Conformance.TestAllTypes.Types.NestedEnum) }, new pbr::GeneratedCodeInfo[] { new pbr::GeneratedCodeInfo(typeof(global::Conformance.TestAllTypes.Types.NestedMessage), new[]{ "A", "Corecursive" }, null, null, null), + null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, }), + new pbr::GeneratedCodeInfo(typeof(global::Conformance.ForeignMessage), new[]{ "C" }, null, null, null) + })); + } + #endregion + + } + #region Enums + public enum WireFormat { + UNSPECIFIED = 0, + PROTOBUF = 1, + JSON = 2, + } + + public enum ForeignEnum { + FOREIGN_FOO = 0, + FOREIGN_BAR = 1, + FOREIGN_BAZ = 2, + } + + #endregion + + #region Messages + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public sealed partial class ConformanceRequest : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new ConformanceRequest()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Conformance.Conformance.Descriptor.MessageTypes[0]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public ConformanceRequest() { + OnConstruction(); + } + + partial void OnConstruction(); + + public ConformanceRequest(ConformanceRequest other) : this() { + requestedOutputFormat_ = other.requestedOutputFormat_; + switch (other.PayloadCase) { + case PayloadOneofCase.ProtobufPayload: + ProtobufPayload = other.ProtobufPayload; + break; + case PayloadOneofCase.JsonPayload: + JsonPayload = other.JsonPayload; + break; + } + + } + + public ConformanceRequest Clone() { + return new ConformanceRequest(this); + } + + public const int ProtobufPayloadFieldNumber = 1; + public pb::ByteString ProtobufPayload { + get { return payloadCase_ == PayloadOneofCase.ProtobufPayload ? (pb::ByteString) payload_ : pb::ByteString.Empty; } + set { + payload_ = pb::Preconditions.CheckNotNull(value, "value"); + payloadCase_ = PayloadOneofCase.ProtobufPayload; + } + } + + public const int JsonPayloadFieldNumber = 2; + public string JsonPayload { + get { return payloadCase_ == PayloadOneofCase.JsonPayload ? (string) payload_ : ""; } + set { + payload_ = pb::Preconditions.CheckNotNull(value, "value"); + payloadCase_ = PayloadOneofCase.JsonPayload; + } + } + + public const int RequestedOutputFormatFieldNumber = 3; + private global::Conformance.WireFormat requestedOutputFormat_ = global::Conformance.WireFormat.UNSPECIFIED; + public global::Conformance.WireFormat RequestedOutputFormat { + get { return requestedOutputFormat_; } + set { + requestedOutputFormat_ = value; + } + } + + private object payload_; + public enum PayloadOneofCase { + None = 0, + ProtobufPayload = 1, + JsonPayload = 2, + } + private PayloadOneofCase payloadCase_ = PayloadOneofCase.None; + public PayloadOneofCase PayloadCase { + get { return payloadCase_; } + } + + public void ClearPayload() { + payloadCase_ = PayloadOneofCase.None; + payload_ = null; + } + + public override bool Equals(object other) { + return Equals(other as ConformanceRequest); + } + + public bool Equals(ConformanceRequest other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (ProtobufPayload != other.ProtobufPayload) return false; + if (JsonPayload != other.JsonPayload) return false; + if (RequestedOutputFormat != other.RequestedOutputFormat) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (payloadCase_ == PayloadOneofCase.ProtobufPayload) hash ^= ProtobufPayload.GetHashCode(); + if (payloadCase_ == PayloadOneofCase.JsonPayload) hash ^= JsonPayload.GetHashCode(); + if (RequestedOutputFormat != global::Conformance.WireFormat.UNSPECIFIED) hash ^= RequestedOutputFormat.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (payloadCase_ == PayloadOneofCase.ProtobufPayload) { + output.WriteRawTag(10); + output.WriteBytes(ProtobufPayload); + } + if (payloadCase_ == PayloadOneofCase.JsonPayload) { + output.WriteRawTag(18); + output.WriteString(JsonPayload); + } + if (RequestedOutputFormat != global::Conformance.WireFormat.UNSPECIFIED) { + output.WriteRawTag(24); + output.WriteEnum((int) RequestedOutputFormat); + } + } + + public int CalculateSize() { + int size = 0; + if (payloadCase_ == PayloadOneofCase.ProtobufPayload) { + size += 1 + pb::CodedOutputStream.ComputeBytesSize(ProtobufPayload); + } + if (payloadCase_ == PayloadOneofCase.JsonPayload) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(JsonPayload); + } + if (RequestedOutputFormat != global::Conformance.WireFormat.UNSPECIFIED) { + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) RequestedOutputFormat); + } + return size; + } + + public void MergeFrom(ConformanceRequest other) { + if (other == null) { + return; + } + if (other.RequestedOutputFormat != global::Conformance.WireFormat.UNSPECIFIED) { + RequestedOutputFormat = other.RequestedOutputFormat; + } + switch (other.PayloadCase) { + case PayloadOneofCase.ProtobufPayload: + ProtobufPayload = other.ProtobufPayload; + break; + case PayloadOneofCase.JsonPayload: + JsonPayload = other.JsonPayload; + break; + } + + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 10: { + ProtobufPayload = input.ReadBytes(); + break; + } + case 18: { + JsonPayload = input.ReadString(); + break; + } + case 24: { + requestedOutputFormat_ = (global::Conformance.WireFormat) input.ReadEnum(); + break; + } + } + } + } + + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public sealed partial class ConformanceResponse : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new ConformanceResponse()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Conformance.Conformance.Descriptor.MessageTypes[1]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public ConformanceResponse() { + OnConstruction(); + } + + partial void OnConstruction(); + + public ConformanceResponse(ConformanceResponse other) : this() { + switch (other.ResultCase) { + case ResultOneofCase.ParseError: + ParseError = other.ParseError; + break; + case ResultOneofCase.RuntimeError: + RuntimeError = other.RuntimeError; + break; + case ResultOneofCase.ProtobufPayload: + ProtobufPayload = other.ProtobufPayload; + break; + case ResultOneofCase.JsonPayload: + JsonPayload = other.JsonPayload; + break; + case ResultOneofCase.Skipped: + Skipped = other.Skipped; + break; + } + + } + + public ConformanceResponse Clone() { + return new ConformanceResponse(this); + } + + public const int ParseErrorFieldNumber = 1; + public string ParseError { + get { return resultCase_ == ResultOneofCase.ParseError ? (string) result_ : ""; } + set { + result_ = pb::Preconditions.CheckNotNull(value, "value"); + resultCase_ = ResultOneofCase.ParseError; + } + } + + public const int RuntimeErrorFieldNumber = 2; + public string RuntimeError { + get { return resultCase_ == ResultOneofCase.RuntimeError ? (string) result_ : ""; } + set { + result_ = pb::Preconditions.CheckNotNull(value, "value"); + resultCase_ = ResultOneofCase.RuntimeError; + } + } + + public const int ProtobufPayloadFieldNumber = 3; + public pb::ByteString ProtobufPayload { + get { return resultCase_ == ResultOneofCase.ProtobufPayload ? (pb::ByteString) result_ : pb::ByteString.Empty; } + set { + result_ = pb::Preconditions.CheckNotNull(value, "value"); + resultCase_ = ResultOneofCase.ProtobufPayload; + } + } + + public const int JsonPayloadFieldNumber = 4; + public string JsonPayload { + get { return resultCase_ == ResultOneofCase.JsonPayload ? (string) result_ : ""; } + set { + result_ = pb::Preconditions.CheckNotNull(value, "value"); + resultCase_ = ResultOneofCase.JsonPayload; + } + } + + public const int SkippedFieldNumber = 5; + public string Skipped { + get { return resultCase_ == ResultOneofCase.Skipped ? (string) result_ : ""; } + set { + result_ = pb::Preconditions.CheckNotNull(value, "value"); + resultCase_ = ResultOneofCase.Skipped; + } + } + + private object result_; + public enum ResultOneofCase { + None = 0, + ParseError = 1, + RuntimeError = 2, + ProtobufPayload = 3, + JsonPayload = 4, + Skipped = 5, + } + private ResultOneofCase resultCase_ = ResultOneofCase.None; + public ResultOneofCase ResultCase { + get { return resultCase_; } + } + + public void ClearResult() { + resultCase_ = ResultOneofCase.None; + result_ = null; + } + + public override bool Equals(object other) { + return Equals(other as ConformanceResponse); + } + + public bool Equals(ConformanceResponse other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (ParseError != other.ParseError) return false; + if (RuntimeError != other.RuntimeError) return false; + if (ProtobufPayload != other.ProtobufPayload) return false; + if (JsonPayload != other.JsonPayload) return false; + if (Skipped != other.Skipped) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (resultCase_ == ResultOneofCase.ParseError) hash ^= ParseError.GetHashCode(); + if (resultCase_ == ResultOneofCase.RuntimeError) hash ^= RuntimeError.GetHashCode(); + if (resultCase_ == ResultOneofCase.ProtobufPayload) hash ^= ProtobufPayload.GetHashCode(); + if (resultCase_ == ResultOneofCase.JsonPayload) hash ^= JsonPayload.GetHashCode(); + if (resultCase_ == ResultOneofCase.Skipped) hash ^= Skipped.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (resultCase_ == ResultOneofCase.ParseError) { + output.WriteRawTag(10); + output.WriteString(ParseError); + } + if (resultCase_ == ResultOneofCase.RuntimeError) { + output.WriteRawTag(18); + output.WriteString(RuntimeError); + } + if (resultCase_ == ResultOneofCase.ProtobufPayload) { + output.WriteRawTag(26); + output.WriteBytes(ProtobufPayload); + } + if (resultCase_ == ResultOneofCase.JsonPayload) { + output.WriteRawTag(34); + output.WriteString(JsonPayload); + } + if (resultCase_ == ResultOneofCase.Skipped) { + output.WriteRawTag(42); + output.WriteString(Skipped); + } + } + + public int CalculateSize() { + int size = 0; + if (resultCase_ == ResultOneofCase.ParseError) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(ParseError); + } + if (resultCase_ == ResultOneofCase.RuntimeError) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(RuntimeError); + } + if (resultCase_ == ResultOneofCase.ProtobufPayload) { + size += 1 + pb::CodedOutputStream.ComputeBytesSize(ProtobufPayload); + } + if (resultCase_ == ResultOneofCase.JsonPayload) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(JsonPayload); + } + if (resultCase_ == ResultOneofCase.Skipped) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Skipped); + } + return size; + } + + public void MergeFrom(ConformanceResponse other) { + if (other == null) { + return; + } + switch (other.ResultCase) { + case ResultOneofCase.ParseError: + ParseError = other.ParseError; + break; + case ResultOneofCase.RuntimeError: + RuntimeError = other.RuntimeError; + break; + case ResultOneofCase.ProtobufPayload: + ProtobufPayload = other.ProtobufPayload; + break; + case ResultOneofCase.JsonPayload: + JsonPayload = other.JsonPayload; + break; + case ResultOneofCase.Skipped: + Skipped = other.Skipped; + break; + } + + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 10: { + ParseError = input.ReadString(); + break; + } + case 18: { + RuntimeError = input.ReadString(); + break; + } + case 26: { + ProtobufPayload = input.ReadBytes(); + break; + } + case 34: { + JsonPayload = input.ReadString(); + break; + } + case 42: { + Skipped = input.ReadString(); + break; + } + } + } + } + + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public sealed partial class TestAllTypes : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new TestAllTypes()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Conformance.Conformance.Descriptor.MessageTypes[2]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public TestAllTypes() { + OnConstruction(); + } + + partial void OnConstruction(); + + public TestAllTypes(TestAllTypes other) : this() { + optionalInt32_ = other.optionalInt32_; + optionalInt64_ = other.optionalInt64_; + optionalUint32_ = other.optionalUint32_; + optionalUint64_ = other.optionalUint64_; + optionalSint32_ = other.optionalSint32_; + optionalSint64_ = other.optionalSint64_; + optionalFixed32_ = other.optionalFixed32_; + optionalFixed64_ = other.optionalFixed64_; + optionalSfixed32_ = other.optionalSfixed32_; + optionalSfixed64_ = other.optionalSfixed64_; + optionalFloat_ = other.optionalFloat_; + optionalDouble_ = other.optionalDouble_; + optionalBool_ = other.optionalBool_; + optionalString_ = other.optionalString_; + optionalBytes_ = other.optionalBytes_; + OptionalNestedMessage = other.optionalNestedMessage_ != null ? other.OptionalNestedMessage.Clone() : null; + OptionalForeignMessage = other.optionalForeignMessage_ != null ? other.OptionalForeignMessage.Clone() : null; + optionalNestedEnum_ = other.optionalNestedEnum_; + optionalForeignEnum_ = other.optionalForeignEnum_; + optionalStringPiece_ = other.optionalStringPiece_; + optionalCord_ = other.optionalCord_; + RecursiveMessage = other.recursiveMessage_ != null ? other.RecursiveMessage.Clone() : null; + repeatedInt32_ = other.repeatedInt32_.Clone(); + repeatedInt64_ = other.repeatedInt64_.Clone(); + repeatedUint32_ = other.repeatedUint32_.Clone(); + repeatedUint64_ = other.repeatedUint64_.Clone(); + repeatedSint32_ = other.repeatedSint32_.Clone(); + repeatedSint64_ = other.repeatedSint64_.Clone(); + repeatedFixed32_ = other.repeatedFixed32_.Clone(); + repeatedFixed64_ = other.repeatedFixed64_.Clone(); + repeatedSfixed32_ = other.repeatedSfixed32_.Clone(); + repeatedSfixed64_ = other.repeatedSfixed64_.Clone(); + repeatedFloat_ = other.repeatedFloat_.Clone(); + repeatedDouble_ = other.repeatedDouble_.Clone(); + repeatedBool_ = other.repeatedBool_.Clone(); + repeatedString_ = other.repeatedString_.Clone(); + repeatedBytes_ = other.repeatedBytes_.Clone(); + repeatedNestedMessage_ = other.repeatedNestedMessage_.Clone(); + repeatedForeignMessage_ = other.repeatedForeignMessage_.Clone(); + repeatedNestedEnum_ = other.repeatedNestedEnum_.Clone(); + repeatedForeignEnum_ = other.repeatedForeignEnum_.Clone(); + repeatedStringPiece_ = other.repeatedStringPiece_.Clone(); + repeatedCord_ = other.repeatedCord_.Clone(); + mapInt32Int32_ = other.mapInt32Int32_.Clone(); + mapInt64Int64_ = other.mapInt64Int64_.Clone(); + mapUint32Uint32_ = other.mapUint32Uint32_.Clone(); + mapUint64Uint64_ = other.mapUint64Uint64_.Clone(); + mapSint32Sint32_ = other.mapSint32Sint32_.Clone(); + mapSint64Sint64_ = other.mapSint64Sint64_.Clone(); + mapFixed32Fixed32_ = other.mapFixed32Fixed32_.Clone(); + mapFixed64Fixed64_ = other.mapFixed64Fixed64_.Clone(); + mapSfixed32Sfixed32_ = other.mapSfixed32Sfixed32_.Clone(); + mapSfixed64Sfixed64_ = other.mapSfixed64Sfixed64_.Clone(); + mapInt32Float_ = other.mapInt32Float_.Clone(); + mapInt32Double_ = other.mapInt32Double_.Clone(); + mapBoolBool_ = other.mapBoolBool_.Clone(); + mapStringString_ = other.mapStringString_.Clone(); + mapStringBytes_ = other.mapStringBytes_.Clone(); + mapStringNestedMessage_ = other.mapStringNestedMessage_.Clone(); + mapStringForeignMessage_ = other.mapStringForeignMessage_.Clone(); + mapStringNestedEnum_ = other.mapStringNestedEnum_.Clone(); + mapStringForeignEnum_ = other.mapStringForeignEnum_.Clone(); + switch (other.OneofFieldCase) { + case OneofFieldOneofCase.OneofUint32: + OneofUint32 = other.OneofUint32; + break; + case OneofFieldOneofCase.OneofNestedMessage: + OneofNestedMessage = other.OneofNestedMessage.Clone(); + break; + case OneofFieldOneofCase.OneofString: + OneofString = other.OneofString; + break; + case OneofFieldOneofCase.OneofBytes: + OneofBytes = other.OneofBytes; + break; + } + + } + + public TestAllTypes Clone() { + return new TestAllTypes(this); + } + + public const int OptionalInt32FieldNumber = 1; + private int optionalInt32_; + public int OptionalInt32 { + get { return optionalInt32_; } + set { + optionalInt32_ = value; + } + } + + public const int OptionalInt64FieldNumber = 2; + private long optionalInt64_; + public long OptionalInt64 { + get { return optionalInt64_; } + set { + optionalInt64_ = value; + } + } + + public const int OptionalUint32FieldNumber = 3; + private uint optionalUint32_; + public uint OptionalUint32 { + get { return optionalUint32_; } + set { + optionalUint32_ = value; + } + } + + public const int OptionalUint64FieldNumber = 4; + private ulong optionalUint64_; + public ulong OptionalUint64 { + get { return optionalUint64_; } + set { + optionalUint64_ = value; + } + } + + public const int OptionalSint32FieldNumber = 5; + private int optionalSint32_; + public int OptionalSint32 { + get { return optionalSint32_; } + set { + optionalSint32_ = value; + } + } + + public const int OptionalSint64FieldNumber = 6; + private long optionalSint64_; + public long OptionalSint64 { + get { return optionalSint64_; } + set { + optionalSint64_ = value; + } + } + + public const int OptionalFixed32FieldNumber = 7; + private uint optionalFixed32_; + public uint OptionalFixed32 { + get { return optionalFixed32_; } + set { + optionalFixed32_ = value; + } + } + + public const int OptionalFixed64FieldNumber = 8; + private ulong optionalFixed64_; + public ulong OptionalFixed64 { + get { return optionalFixed64_; } + set { + optionalFixed64_ = value; + } + } + + public const int OptionalSfixed32FieldNumber = 9; + private int optionalSfixed32_; + public int OptionalSfixed32 { + get { return optionalSfixed32_; } + set { + optionalSfixed32_ = value; + } + } + + public const int OptionalSfixed64FieldNumber = 10; + private long optionalSfixed64_; + public long OptionalSfixed64 { + get { return optionalSfixed64_; } + set { + optionalSfixed64_ = value; + } + } + + public const int OptionalFloatFieldNumber = 11; + private float optionalFloat_; + public float OptionalFloat { + get { return optionalFloat_; } + set { + optionalFloat_ = value; + } + } + + public const int OptionalDoubleFieldNumber = 12; + private double optionalDouble_; + public double OptionalDouble { + get { return optionalDouble_; } + set { + optionalDouble_ = value; + } + } + + public const int OptionalBoolFieldNumber = 13; + private bool optionalBool_; + public bool OptionalBool { + get { return optionalBool_; } + set { + optionalBool_ = value; + } + } + + public const int OptionalStringFieldNumber = 14; + private string optionalString_ = ""; + public string OptionalString { + get { return optionalString_; } + set { + optionalString_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int OptionalBytesFieldNumber = 15; + private pb::ByteString optionalBytes_ = pb::ByteString.Empty; + public pb::ByteString OptionalBytes { + get { return optionalBytes_; } + set { + optionalBytes_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int OptionalNestedMessageFieldNumber = 18; + private global::Conformance.TestAllTypes.Types.NestedMessage optionalNestedMessage_; + public global::Conformance.TestAllTypes.Types.NestedMessage OptionalNestedMessage { + get { return optionalNestedMessage_; } + set { + optionalNestedMessage_ = value; + } + } + + public const int OptionalForeignMessageFieldNumber = 19; + private global::Conformance.ForeignMessage optionalForeignMessage_; + public global::Conformance.ForeignMessage OptionalForeignMessage { + get { return optionalForeignMessage_; } + set { + optionalForeignMessage_ = value; + } + } + + public const int OptionalNestedEnumFieldNumber = 21; + private global::Conformance.TestAllTypes.Types.NestedEnum optionalNestedEnum_ = global::Conformance.TestAllTypes.Types.NestedEnum.FOO; + public global::Conformance.TestAllTypes.Types.NestedEnum OptionalNestedEnum { + get { return optionalNestedEnum_; } + set { + optionalNestedEnum_ = value; + } + } + + public const int OptionalForeignEnumFieldNumber = 22; + private global::Conformance.ForeignEnum optionalForeignEnum_ = global::Conformance.ForeignEnum.FOREIGN_FOO; + public global::Conformance.ForeignEnum OptionalForeignEnum { + get { return optionalForeignEnum_; } + set { + optionalForeignEnum_ = value; + } + } + + public const int OptionalStringPieceFieldNumber = 24; + private string optionalStringPiece_ = ""; + public string OptionalStringPiece { + get { return optionalStringPiece_; } + set { + optionalStringPiece_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int OptionalCordFieldNumber = 25; + private string optionalCord_ = ""; + public string OptionalCord { + get { return optionalCord_; } + set { + optionalCord_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int RecursiveMessageFieldNumber = 27; + private global::Conformance.TestAllTypes recursiveMessage_; + public global::Conformance.TestAllTypes RecursiveMessage { + get { return recursiveMessage_; } + set { + recursiveMessage_ = value; + } + } + + public const int RepeatedInt32FieldNumber = 31; + private static readonly pb::FieldCodec _repeated_repeatedInt32_codec + = pb::FieldCodec.ForInt32(250); + private readonly pbc::RepeatedField repeatedInt32_ = new pbc::RepeatedField(); + public pbc::RepeatedField RepeatedInt32 { + get { return repeatedInt32_; } + } + + public const int RepeatedInt64FieldNumber = 32; + private static readonly pb::FieldCodec _repeated_repeatedInt64_codec + = pb::FieldCodec.ForInt64(258); + private readonly pbc::RepeatedField repeatedInt64_ = new pbc::RepeatedField(); + public pbc::RepeatedField RepeatedInt64 { + get { return repeatedInt64_; } + } + + public const int RepeatedUint32FieldNumber = 33; + private static readonly pb::FieldCodec _repeated_repeatedUint32_codec + = pb::FieldCodec.ForUInt32(266); + private readonly pbc::RepeatedField repeatedUint32_ = new pbc::RepeatedField(); + public pbc::RepeatedField RepeatedUint32 { + get { return repeatedUint32_; } + } + + public const int RepeatedUint64FieldNumber = 34; + private static readonly pb::FieldCodec _repeated_repeatedUint64_codec + = pb::FieldCodec.ForUInt64(274); + private readonly pbc::RepeatedField repeatedUint64_ = new pbc::RepeatedField(); + public pbc::RepeatedField RepeatedUint64 { + get { return repeatedUint64_; } + } + + public const int RepeatedSint32FieldNumber = 35; + private static readonly pb::FieldCodec _repeated_repeatedSint32_codec + = pb::FieldCodec.ForSInt32(282); + private readonly pbc::RepeatedField repeatedSint32_ = new pbc::RepeatedField(); + public pbc::RepeatedField RepeatedSint32 { + get { return repeatedSint32_; } + } + + public const int RepeatedSint64FieldNumber = 36; + private static readonly pb::FieldCodec _repeated_repeatedSint64_codec + = pb::FieldCodec.ForSInt64(290); + private readonly pbc::RepeatedField repeatedSint64_ = new pbc::RepeatedField(); + public pbc::RepeatedField RepeatedSint64 { + get { return repeatedSint64_; } + } + + public const int RepeatedFixed32FieldNumber = 37; + private static readonly pb::FieldCodec _repeated_repeatedFixed32_codec + = pb::FieldCodec.ForFixed32(298); + private readonly pbc::RepeatedField repeatedFixed32_ = new pbc::RepeatedField(); + public pbc::RepeatedField RepeatedFixed32 { + get { return repeatedFixed32_; } + } + + public const int RepeatedFixed64FieldNumber = 38; + private static readonly pb::FieldCodec _repeated_repeatedFixed64_codec + = pb::FieldCodec.ForFixed64(306); + private readonly pbc::RepeatedField repeatedFixed64_ = new pbc::RepeatedField(); + public pbc::RepeatedField RepeatedFixed64 { + get { return repeatedFixed64_; } + } + + public const int RepeatedSfixed32FieldNumber = 39; + private static readonly pb::FieldCodec _repeated_repeatedSfixed32_codec + = pb::FieldCodec.ForSFixed32(314); + private readonly pbc::RepeatedField repeatedSfixed32_ = new pbc::RepeatedField(); + public pbc::RepeatedField RepeatedSfixed32 { + get { return repeatedSfixed32_; } + } + + public const int RepeatedSfixed64FieldNumber = 40; + private static readonly pb::FieldCodec _repeated_repeatedSfixed64_codec + = pb::FieldCodec.ForSFixed64(322); + private readonly pbc::RepeatedField repeatedSfixed64_ = new pbc::RepeatedField(); + public pbc::RepeatedField RepeatedSfixed64 { + get { return repeatedSfixed64_; } + } + + public const int RepeatedFloatFieldNumber = 41; + private static readonly pb::FieldCodec _repeated_repeatedFloat_codec + = pb::FieldCodec.ForFloat(330); + private readonly pbc::RepeatedField repeatedFloat_ = new pbc::RepeatedField(); + public pbc::RepeatedField RepeatedFloat { + get { return repeatedFloat_; } + } + + public const int RepeatedDoubleFieldNumber = 42; + private static readonly pb::FieldCodec _repeated_repeatedDouble_codec + = pb::FieldCodec.ForDouble(338); + private readonly pbc::RepeatedField repeatedDouble_ = new pbc::RepeatedField(); + public pbc::RepeatedField RepeatedDouble { + get { return repeatedDouble_; } + } + + public const int RepeatedBoolFieldNumber = 43; + private static readonly pb::FieldCodec _repeated_repeatedBool_codec + = pb::FieldCodec.ForBool(346); + private readonly pbc::RepeatedField repeatedBool_ = new pbc::RepeatedField(); + public pbc::RepeatedField RepeatedBool { + get { return repeatedBool_; } + } + + public const int RepeatedStringFieldNumber = 44; + private static readonly pb::FieldCodec _repeated_repeatedString_codec + = pb::FieldCodec.ForString(354); + private readonly pbc::RepeatedField repeatedString_ = new pbc::RepeatedField(); + public pbc::RepeatedField RepeatedString { + get { return repeatedString_; } + } + + public const int RepeatedBytesFieldNumber = 45; + private static readonly pb::FieldCodec _repeated_repeatedBytes_codec + = pb::FieldCodec.ForBytes(362); + private readonly pbc::RepeatedField repeatedBytes_ = new pbc::RepeatedField(); + public pbc::RepeatedField RepeatedBytes { + get { return repeatedBytes_; } + } + + public const int RepeatedNestedMessageFieldNumber = 48; + private static readonly pb::FieldCodec _repeated_repeatedNestedMessage_codec + = pb::FieldCodec.ForMessage(386, global::Conformance.TestAllTypes.Types.NestedMessage.Parser); + private readonly pbc::RepeatedField repeatedNestedMessage_ = new pbc::RepeatedField(); + public pbc::RepeatedField RepeatedNestedMessage { + get { return repeatedNestedMessage_; } + } + + public const int RepeatedForeignMessageFieldNumber = 49; + private static readonly pb::FieldCodec _repeated_repeatedForeignMessage_codec + = pb::FieldCodec.ForMessage(394, global::Conformance.ForeignMessage.Parser); + private readonly pbc::RepeatedField repeatedForeignMessage_ = new pbc::RepeatedField(); + public pbc::RepeatedField RepeatedForeignMessage { + get { return repeatedForeignMessage_; } + } + + public const int RepeatedNestedEnumFieldNumber = 51; + private static readonly pb::FieldCodec _repeated_repeatedNestedEnum_codec + = pb::FieldCodec.ForEnum(410, x => (int) x, x => (global::Conformance.TestAllTypes.Types.NestedEnum) x); + private readonly pbc::RepeatedField repeatedNestedEnum_ = new pbc::RepeatedField(); + public pbc::RepeatedField RepeatedNestedEnum { + get { return repeatedNestedEnum_; } + } + + public const int RepeatedForeignEnumFieldNumber = 52; + private static readonly pb::FieldCodec _repeated_repeatedForeignEnum_codec + = pb::FieldCodec.ForEnum(418, x => (int) x, x => (global::Conformance.ForeignEnum) x); + private readonly pbc::RepeatedField repeatedForeignEnum_ = new pbc::RepeatedField(); + public pbc::RepeatedField RepeatedForeignEnum { + get { return repeatedForeignEnum_; } + } + + public const int RepeatedStringPieceFieldNumber = 54; + private static readonly pb::FieldCodec _repeated_repeatedStringPiece_codec + = pb::FieldCodec.ForString(434); + private readonly pbc::RepeatedField repeatedStringPiece_ = new pbc::RepeatedField(); + public pbc::RepeatedField RepeatedStringPiece { + get { return repeatedStringPiece_; } + } + + public const int RepeatedCordFieldNumber = 55; + private static readonly pb::FieldCodec _repeated_repeatedCord_codec + = pb::FieldCodec.ForString(442); + private readonly pbc::RepeatedField repeatedCord_ = new pbc::RepeatedField(); + public pbc::RepeatedField RepeatedCord { + get { return repeatedCord_; } + } + + public const int MapInt32Int32FieldNumber = 56; + private static readonly pbc::MapField.Codec _map_mapInt32Int32_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForInt32(8), pb::FieldCodec.ForInt32(16), 450); + private readonly pbc::MapField mapInt32Int32_ = new pbc::MapField(); + public pbc::MapField MapInt32Int32 { + get { return mapInt32Int32_; } + } + + public const int MapInt64Int64FieldNumber = 57; + private static readonly pbc::MapField.Codec _map_mapInt64Int64_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForInt64(8), pb::FieldCodec.ForInt64(16), 458); + private readonly pbc::MapField mapInt64Int64_ = new pbc::MapField(); + public pbc::MapField MapInt64Int64 { + get { return mapInt64Int64_; } + } + + public const int MapUint32Uint32FieldNumber = 58; + private static readonly pbc::MapField.Codec _map_mapUint32Uint32_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForUInt32(8), pb::FieldCodec.ForUInt32(16), 466); + private readonly pbc::MapField mapUint32Uint32_ = new pbc::MapField(); + public pbc::MapField MapUint32Uint32 { + get { return mapUint32Uint32_; } + } + + public const int MapUint64Uint64FieldNumber = 59; + private static readonly pbc::MapField.Codec _map_mapUint64Uint64_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForUInt64(8), pb::FieldCodec.ForUInt64(16), 474); + private readonly pbc::MapField mapUint64Uint64_ = new pbc::MapField(); + public pbc::MapField MapUint64Uint64 { + get { return mapUint64Uint64_; } + } + + public const int MapSint32Sint32FieldNumber = 60; + private static readonly pbc::MapField.Codec _map_mapSint32Sint32_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForSInt32(8), pb::FieldCodec.ForSInt32(16), 482); + private readonly pbc::MapField mapSint32Sint32_ = new pbc::MapField(); + public pbc::MapField MapSint32Sint32 { + get { return mapSint32Sint32_; } + } + + public const int MapSint64Sint64FieldNumber = 61; + private static readonly pbc::MapField.Codec _map_mapSint64Sint64_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForSInt64(8), pb::FieldCodec.ForSInt64(16), 490); + private readonly pbc::MapField mapSint64Sint64_ = new pbc::MapField(); + public pbc::MapField MapSint64Sint64 { + get { return mapSint64Sint64_; } + } + + public const int MapFixed32Fixed32FieldNumber = 62; + private static readonly pbc::MapField.Codec _map_mapFixed32Fixed32_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForFixed32(13), pb::FieldCodec.ForFixed32(21), 498); + private readonly pbc::MapField mapFixed32Fixed32_ = new pbc::MapField(); + public pbc::MapField MapFixed32Fixed32 { + get { return mapFixed32Fixed32_; } + } + + public const int MapFixed64Fixed64FieldNumber = 63; + private static readonly pbc::MapField.Codec _map_mapFixed64Fixed64_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForFixed64(9), pb::FieldCodec.ForFixed64(17), 506); + private readonly pbc::MapField mapFixed64Fixed64_ = new pbc::MapField(); + public pbc::MapField MapFixed64Fixed64 { + get { return mapFixed64Fixed64_; } + } + + public const int MapSfixed32Sfixed32FieldNumber = 64; + private static readonly pbc::MapField.Codec _map_mapSfixed32Sfixed32_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForSFixed32(13), pb::FieldCodec.ForSFixed32(21), 514); + private readonly pbc::MapField mapSfixed32Sfixed32_ = new pbc::MapField(); + public pbc::MapField MapSfixed32Sfixed32 { + get { return mapSfixed32Sfixed32_; } + } + + public const int MapSfixed64Sfixed64FieldNumber = 65; + private static readonly pbc::MapField.Codec _map_mapSfixed64Sfixed64_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForSFixed64(9), pb::FieldCodec.ForSFixed64(17), 522); + private readonly pbc::MapField mapSfixed64Sfixed64_ = new pbc::MapField(); + public pbc::MapField MapSfixed64Sfixed64 { + get { return mapSfixed64Sfixed64_; } + } + + public const int MapInt32FloatFieldNumber = 66; + private static readonly pbc::MapField.Codec _map_mapInt32Float_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForInt32(8), pb::FieldCodec.ForFloat(21), 530); + private readonly pbc::MapField mapInt32Float_ = new pbc::MapField(); + public pbc::MapField MapInt32Float { + get { return mapInt32Float_; } + } + + public const int MapInt32DoubleFieldNumber = 67; + private static readonly pbc::MapField.Codec _map_mapInt32Double_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForInt32(8), pb::FieldCodec.ForDouble(17), 538); + private readonly pbc::MapField mapInt32Double_ = new pbc::MapField(); + public pbc::MapField MapInt32Double { + get { return mapInt32Double_; } + } + + public const int MapBoolBoolFieldNumber = 68; + private static readonly pbc::MapField.Codec _map_mapBoolBool_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForBool(8), pb::FieldCodec.ForBool(16), 546); + private readonly pbc::MapField mapBoolBool_ = new pbc::MapField(); + public pbc::MapField MapBoolBool { + get { return mapBoolBool_; } + } + + public const int MapStringStringFieldNumber = 69; + private static readonly pbc::MapField.Codec _map_mapStringString_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForString(10), pb::FieldCodec.ForString(18), 554); + private readonly pbc::MapField mapStringString_ = new pbc::MapField(); + public pbc::MapField MapStringString { + get { return mapStringString_; } + } + + public const int MapStringBytesFieldNumber = 70; + private static readonly pbc::MapField.Codec _map_mapStringBytes_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForString(10), pb::FieldCodec.ForBytes(18), 562); + private readonly pbc::MapField mapStringBytes_ = new pbc::MapField(); + public pbc::MapField MapStringBytes { + get { return mapStringBytes_; } + } + + public const int MapStringNestedMessageFieldNumber = 71; + private static readonly pbc::MapField.Codec _map_mapStringNestedMessage_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForString(10), pb::FieldCodec.ForMessage(18, global::Conformance.TestAllTypes.Types.NestedMessage.Parser), 570); + private readonly pbc::MapField mapStringNestedMessage_ = new pbc::MapField(); + public pbc::MapField MapStringNestedMessage { + get { return mapStringNestedMessage_; } + } + + public const int MapStringForeignMessageFieldNumber = 72; + private static readonly pbc::MapField.Codec _map_mapStringForeignMessage_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForString(10), pb::FieldCodec.ForMessage(18, global::Conformance.ForeignMessage.Parser), 578); + private readonly pbc::MapField mapStringForeignMessage_ = new pbc::MapField(); + public pbc::MapField MapStringForeignMessage { + get { return mapStringForeignMessage_; } + } + + public const int MapStringNestedEnumFieldNumber = 73; + private static readonly pbc::MapField.Codec _map_mapStringNestedEnum_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForString(10), pb::FieldCodec.ForEnum(16, x => (int) x, x => (global::Conformance.TestAllTypes.Types.NestedEnum) x), 586); + private readonly pbc::MapField mapStringNestedEnum_ = new pbc::MapField(); + public pbc::MapField MapStringNestedEnum { + get { return mapStringNestedEnum_; } + } + + public const int MapStringForeignEnumFieldNumber = 74; + private static readonly pbc::MapField.Codec _map_mapStringForeignEnum_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForString(10), pb::FieldCodec.ForEnum(16, x => (int) x, x => (global::Conformance.ForeignEnum) x), 594); + private readonly pbc::MapField mapStringForeignEnum_ = new pbc::MapField(); + public pbc::MapField MapStringForeignEnum { + get { return mapStringForeignEnum_; } + } + + public const int OneofUint32FieldNumber = 111; + public uint OneofUint32 { + get { return oneofFieldCase_ == OneofFieldOneofCase.OneofUint32 ? (uint) oneofField_ : 0; } + set { + oneofField_ = value; + oneofFieldCase_ = OneofFieldOneofCase.OneofUint32; + } + } + + public const int OneofNestedMessageFieldNumber = 112; + public global::Conformance.TestAllTypes.Types.NestedMessage OneofNestedMessage { + get { return oneofFieldCase_ == OneofFieldOneofCase.OneofNestedMessage ? (global::Conformance.TestAllTypes.Types.NestedMessage) oneofField_ : null; } + set { + oneofField_ = value; + oneofFieldCase_ = value == null ? OneofFieldOneofCase.None : OneofFieldOneofCase.OneofNestedMessage; + } + } + + public const int OneofStringFieldNumber = 113; + public string OneofString { + get { return oneofFieldCase_ == OneofFieldOneofCase.OneofString ? (string) oneofField_ : ""; } + set { + oneofField_ = pb::Preconditions.CheckNotNull(value, "value"); + oneofFieldCase_ = OneofFieldOneofCase.OneofString; + } + } + + public const int OneofBytesFieldNumber = 114; + public pb::ByteString OneofBytes { + get { return oneofFieldCase_ == OneofFieldOneofCase.OneofBytes ? (pb::ByteString) oneofField_ : pb::ByteString.Empty; } + set { + oneofField_ = pb::Preconditions.CheckNotNull(value, "value"); + oneofFieldCase_ = OneofFieldOneofCase.OneofBytes; + } + } + + private object oneofField_; + public enum OneofFieldOneofCase { + None = 0, + OneofUint32 = 111, + OneofNestedMessage = 112, + OneofString = 113, + OneofBytes = 114, + } + private OneofFieldOneofCase oneofFieldCase_ = OneofFieldOneofCase.None; + public OneofFieldOneofCase OneofFieldCase { + get { return oneofFieldCase_; } + } + + public void ClearOneofField() { + oneofFieldCase_ = OneofFieldOneofCase.None; + oneofField_ = null; + } + + public override bool Equals(object other) { + return Equals(other as TestAllTypes); + } + + public bool Equals(TestAllTypes other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (OptionalInt32 != other.OptionalInt32) return false; + if (OptionalInt64 != other.OptionalInt64) return false; + if (OptionalUint32 != other.OptionalUint32) return false; + if (OptionalUint64 != other.OptionalUint64) return false; + if (OptionalSint32 != other.OptionalSint32) return false; + if (OptionalSint64 != other.OptionalSint64) return false; + if (OptionalFixed32 != other.OptionalFixed32) return false; + if (OptionalFixed64 != other.OptionalFixed64) return false; + if (OptionalSfixed32 != other.OptionalSfixed32) return false; + if (OptionalSfixed64 != other.OptionalSfixed64) return false; + if (OptionalFloat != other.OptionalFloat) return false; + if (OptionalDouble != other.OptionalDouble) return false; + if (OptionalBool != other.OptionalBool) return false; + if (OptionalString != other.OptionalString) return false; + if (OptionalBytes != other.OptionalBytes) return false; + if (!object.Equals(OptionalNestedMessage, other.OptionalNestedMessage)) return false; + if (!object.Equals(OptionalForeignMessage, other.OptionalForeignMessage)) return false; + if (OptionalNestedEnum != other.OptionalNestedEnum) return false; + if (OptionalForeignEnum != other.OptionalForeignEnum) return false; + if (OptionalStringPiece != other.OptionalStringPiece) return false; + if (OptionalCord != other.OptionalCord) return false; + if (!object.Equals(RecursiveMessage, other.RecursiveMessage)) return false; + if(!repeatedInt32_.Equals(other.repeatedInt32_)) return false; + if(!repeatedInt64_.Equals(other.repeatedInt64_)) return false; + if(!repeatedUint32_.Equals(other.repeatedUint32_)) return false; + if(!repeatedUint64_.Equals(other.repeatedUint64_)) return false; + if(!repeatedSint32_.Equals(other.repeatedSint32_)) return false; + if(!repeatedSint64_.Equals(other.repeatedSint64_)) return false; + if(!repeatedFixed32_.Equals(other.repeatedFixed32_)) return false; + if(!repeatedFixed64_.Equals(other.repeatedFixed64_)) return false; + if(!repeatedSfixed32_.Equals(other.repeatedSfixed32_)) return false; + if(!repeatedSfixed64_.Equals(other.repeatedSfixed64_)) return false; + if(!repeatedFloat_.Equals(other.repeatedFloat_)) return false; + if(!repeatedDouble_.Equals(other.repeatedDouble_)) return false; + if(!repeatedBool_.Equals(other.repeatedBool_)) return false; + if(!repeatedString_.Equals(other.repeatedString_)) return false; + if(!repeatedBytes_.Equals(other.repeatedBytes_)) return false; + if(!repeatedNestedMessage_.Equals(other.repeatedNestedMessage_)) return false; + if(!repeatedForeignMessage_.Equals(other.repeatedForeignMessage_)) return false; + if(!repeatedNestedEnum_.Equals(other.repeatedNestedEnum_)) return false; + if(!repeatedForeignEnum_.Equals(other.repeatedForeignEnum_)) return false; + if(!repeatedStringPiece_.Equals(other.repeatedStringPiece_)) return false; + if(!repeatedCord_.Equals(other.repeatedCord_)) return false; + if (!MapInt32Int32.Equals(other.MapInt32Int32)) return false; + if (!MapInt64Int64.Equals(other.MapInt64Int64)) return false; + if (!MapUint32Uint32.Equals(other.MapUint32Uint32)) return false; + if (!MapUint64Uint64.Equals(other.MapUint64Uint64)) return false; + if (!MapSint32Sint32.Equals(other.MapSint32Sint32)) return false; + if (!MapSint64Sint64.Equals(other.MapSint64Sint64)) return false; + if (!MapFixed32Fixed32.Equals(other.MapFixed32Fixed32)) return false; + if (!MapFixed64Fixed64.Equals(other.MapFixed64Fixed64)) return false; + if (!MapSfixed32Sfixed32.Equals(other.MapSfixed32Sfixed32)) return false; + if (!MapSfixed64Sfixed64.Equals(other.MapSfixed64Sfixed64)) return false; + if (!MapInt32Float.Equals(other.MapInt32Float)) return false; + if (!MapInt32Double.Equals(other.MapInt32Double)) return false; + if (!MapBoolBool.Equals(other.MapBoolBool)) return false; + if (!MapStringString.Equals(other.MapStringString)) return false; + if (!MapStringBytes.Equals(other.MapStringBytes)) return false; + if (!MapStringNestedMessage.Equals(other.MapStringNestedMessage)) return false; + if (!MapStringForeignMessage.Equals(other.MapStringForeignMessage)) return false; + if (!MapStringNestedEnum.Equals(other.MapStringNestedEnum)) return false; + if (!MapStringForeignEnum.Equals(other.MapStringForeignEnum)) return false; + if (OneofUint32 != other.OneofUint32) return false; + if (!object.Equals(OneofNestedMessage, other.OneofNestedMessage)) return false; + if (OneofString != other.OneofString) return false; + if (OneofBytes != other.OneofBytes) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (OptionalInt32 != 0) hash ^= OptionalInt32.GetHashCode(); + if (OptionalInt64 != 0L) hash ^= OptionalInt64.GetHashCode(); + if (OptionalUint32 != 0) hash ^= OptionalUint32.GetHashCode(); + if (OptionalUint64 != 0UL) hash ^= OptionalUint64.GetHashCode(); + if (OptionalSint32 != 0) hash ^= OptionalSint32.GetHashCode(); + if (OptionalSint64 != 0L) hash ^= OptionalSint64.GetHashCode(); + if (OptionalFixed32 != 0) hash ^= OptionalFixed32.GetHashCode(); + if (OptionalFixed64 != 0UL) hash ^= OptionalFixed64.GetHashCode(); + if (OptionalSfixed32 != 0) hash ^= OptionalSfixed32.GetHashCode(); + if (OptionalSfixed64 != 0L) hash ^= OptionalSfixed64.GetHashCode(); + if (OptionalFloat != 0F) hash ^= OptionalFloat.GetHashCode(); + if (OptionalDouble != 0D) hash ^= OptionalDouble.GetHashCode(); + if (OptionalBool != false) hash ^= OptionalBool.GetHashCode(); + if (OptionalString.Length != 0) hash ^= OptionalString.GetHashCode(); + if (OptionalBytes.Length != 0) hash ^= OptionalBytes.GetHashCode(); + if (optionalNestedMessage_ != null) hash ^= OptionalNestedMessage.GetHashCode(); + if (optionalForeignMessage_ != null) hash ^= OptionalForeignMessage.GetHashCode(); + if (OptionalNestedEnum != global::Conformance.TestAllTypes.Types.NestedEnum.FOO) hash ^= OptionalNestedEnum.GetHashCode(); + if (OptionalForeignEnum != global::Conformance.ForeignEnum.FOREIGN_FOO) hash ^= OptionalForeignEnum.GetHashCode(); + if (OptionalStringPiece.Length != 0) hash ^= OptionalStringPiece.GetHashCode(); + if (OptionalCord.Length != 0) hash ^= OptionalCord.GetHashCode(); + if (recursiveMessage_ != null) hash ^= RecursiveMessage.GetHashCode(); + hash ^= repeatedInt32_.GetHashCode(); + hash ^= repeatedInt64_.GetHashCode(); + hash ^= repeatedUint32_.GetHashCode(); + hash ^= repeatedUint64_.GetHashCode(); + hash ^= repeatedSint32_.GetHashCode(); + hash ^= repeatedSint64_.GetHashCode(); + hash ^= repeatedFixed32_.GetHashCode(); + hash ^= repeatedFixed64_.GetHashCode(); + hash ^= repeatedSfixed32_.GetHashCode(); + hash ^= repeatedSfixed64_.GetHashCode(); + hash ^= repeatedFloat_.GetHashCode(); + hash ^= repeatedDouble_.GetHashCode(); + hash ^= repeatedBool_.GetHashCode(); + hash ^= repeatedString_.GetHashCode(); + hash ^= repeatedBytes_.GetHashCode(); + hash ^= repeatedNestedMessage_.GetHashCode(); + hash ^= repeatedForeignMessage_.GetHashCode(); + hash ^= repeatedNestedEnum_.GetHashCode(); + hash ^= repeatedForeignEnum_.GetHashCode(); + hash ^= repeatedStringPiece_.GetHashCode(); + hash ^= repeatedCord_.GetHashCode(); + hash ^= MapInt32Int32.GetHashCode(); + hash ^= MapInt64Int64.GetHashCode(); + hash ^= MapUint32Uint32.GetHashCode(); + hash ^= MapUint64Uint64.GetHashCode(); + hash ^= MapSint32Sint32.GetHashCode(); + hash ^= MapSint64Sint64.GetHashCode(); + hash ^= MapFixed32Fixed32.GetHashCode(); + hash ^= MapFixed64Fixed64.GetHashCode(); + hash ^= MapSfixed32Sfixed32.GetHashCode(); + hash ^= MapSfixed64Sfixed64.GetHashCode(); + hash ^= MapInt32Float.GetHashCode(); + hash ^= MapInt32Double.GetHashCode(); + hash ^= MapBoolBool.GetHashCode(); + hash ^= MapStringString.GetHashCode(); + hash ^= MapStringBytes.GetHashCode(); + hash ^= MapStringNestedMessage.GetHashCode(); + hash ^= MapStringForeignMessage.GetHashCode(); + hash ^= MapStringNestedEnum.GetHashCode(); + hash ^= MapStringForeignEnum.GetHashCode(); + if (oneofFieldCase_ == OneofFieldOneofCase.OneofUint32) hash ^= OneofUint32.GetHashCode(); + if (oneofFieldCase_ == OneofFieldOneofCase.OneofNestedMessage) hash ^= OneofNestedMessage.GetHashCode(); + if (oneofFieldCase_ == OneofFieldOneofCase.OneofString) hash ^= OneofString.GetHashCode(); + if (oneofFieldCase_ == OneofFieldOneofCase.OneofBytes) hash ^= OneofBytes.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (OptionalInt32 != 0) { + output.WriteRawTag(8); + output.WriteInt32(OptionalInt32); + } + if (OptionalInt64 != 0L) { + output.WriteRawTag(16); + output.WriteInt64(OptionalInt64); + } + if (OptionalUint32 != 0) { + output.WriteRawTag(24); + output.WriteUInt32(OptionalUint32); + } + if (OptionalUint64 != 0UL) { + output.WriteRawTag(32); + output.WriteUInt64(OptionalUint64); + } + if (OptionalSint32 != 0) { + output.WriteRawTag(40); + output.WriteSInt32(OptionalSint32); + } + if (OptionalSint64 != 0L) { + output.WriteRawTag(48); + output.WriteSInt64(OptionalSint64); + } + if (OptionalFixed32 != 0) { + output.WriteRawTag(61); + output.WriteFixed32(OptionalFixed32); + } + if (OptionalFixed64 != 0UL) { + output.WriteRawTag(65); + output.WriteFixed64(OptionalFixed64); + } + if (OptionalSfixed32 != 0) { + output.WriteRawTag(77); + output.WriteSFixed32(OptionalSfixed32); + } + if (OptionalSfixed64 != 0L) { + output.WriteRawTag(81); + output.WriteSFixed64(OptionalSfixed64); + } + if (OptionalFloat != 0F) { + output.WriteRawTag(93); + output.WriteFloat(OptionalFloat); + } + if (OptionalDouble != 0D) { + output.WriteRawTag(97); + output.WriteDouble(OptionalDouble); + } + if (OptionalBool != false) { + output.WriteRawTag(104); + output.WriteBool(OptionalBool); + } + if (OptionalString.Length != 0) { + output.WriteRawTag(114); + output.WriteString(OptionalString); + } + if (OptionalBytes.Length != 0) { + output.WriteRawTag(122); + output.WriteBytes(OptionalBytes); + } + if (optionalNestedMessage_ != null) { + output.WriteRawTag(146, 1); + output.WriteMessage(OptionalNestedMessage); + } + if (optionalForeignMessage_ != null) { + output.WriteRawTag(154, 1); + output.WriteMessage(OptionalForeignMessage); + } + if (OptionalNestedEnum != global::Conformance.TestAllTypes.Types.NestedEnum.FOO) { + output.WriteRawTag(168, 1); + output.WriteEnum((int) OptionalNestedEnum); + } + if (OptionalForeignEnum != global::Conformance.ForeignEnum.FOREIGN_FOO) { + output.WriteRawTag(176, 1); + output.WriteEnum((int) OptionalForeignEnum); + } + if (OptionalStringPiece.Length != 0) { + output.WriteRawTag(194, 1); + output.WriteString(OptionalStringPiece); + } + if (OptionalCord.Length != 0) { + output.WriteRawTag(202, 1); + output.WriteString(OptionalCord); + } + if (recursiveMessage_ != null) { + output.WriteRawTag(218, 1); + output.WriteMessage(RecursiveMessage); + } + repeatedInt32_.WriteTo(output, _repeated_repeatedInt32_codec); + repeatedInt64_.WriteTo(output, _repeated_repeatedInt64_codec); + repeatedUint32_.WriteTo(output, _repeated_repeatedUint32_codec); + repeatedUint64_.WriteTo(output, _repeated_repeatedUint64_codec); + repeatedSint32_.WriteTo(output, _repeated_repeatedSint32_codec); + repeatedSint64_.WriteTo(output, _repeated_repeatedSint64_codec); + repeatedFixed32_.WriteTo(output, _repeated_repeatedFixed32_codec); + repeatedFixed64_.WriteTo(output, _repeated_repeatedFixed64_codec); + repeatedSfixed32_.WriteTo(output, _repeated_repeatedSfixed32_codec); + repeatedSfixed64_.WriteTo(output, _repeated_repeatedSfixed64_codec); + repeatedFloat_.WriteTo(output, _repeated_repeatedFloat_codec); + repeatedDouble_.WriteTo(output, _repeated_repeatedDouble_codec); + repeatedBool_.WriteTo(output, _repeated_repeatedBool_codec); + repeatedString_.WriteTo(output, _repeated_repeatedString_codec); + repeatedBytes_.WriteTo(output, _repeated_repeatedBytes_codec); + repeatedNestedMessage_.WriteTo(output, _repeated_repeatedNestedMessage_codec); + repeatedForeignMessage_.WriteTo(output, _repeated_repeatedForeignMessage_codec); + repeatedNestedEnum_.WriteTo(output, _repeated_repeatedNestedEnum_codec); + repeatedForeignEnum_.WriteTo(output, _repeated_repeatedForeignEnum_codec); + repeatedStringPiece_.WriteTo(output, _repeated_repeatedStringPiece_codec); + repeatedCord_.WriteTo(output, _repeated_repeatedCord_codec); + mapInt32Int32_.WriteTo(output, _map_mapInt32Int32_codec); + mapInt64Int64_.WriteTo(output, _map_mapInt64Int64_codec); + mapUint32Uint32_.WriteTo(output, _map_mapUint32Uint32_codec); + mapUint64Uint64_.WriteTo(output, _map_mapUint64Uint64_codec); + mapSint32Sint32_.WriteTo(output, _map_mapSint32Sint32_codec); + mapSint64Sint64_.WriteTo(output, _map_mapSint64Sint64_codec); + mapFixed32Fixed32_.WriteTo(output, _map_mapFixed32Fixed32_codec); + mapFixed64Fixed64_.WriteTo(output, _map_mapFixed64Fixed64_codec); + mapSfixed32Sfixed32_.WriteTo(output, _map_mapSfixed32Sfixed32_codec); + mapSfixed64Sfixed64_.WriteTo(output, _map_mapSfixed64Sfixed64_codec); + mapInt32Float_.WriteTo(output, _map_mapInt32Float_codec); + mapInt32Double_.WriteTo(output, _map_mapInt32Double_codec); + mapBoolBool_.WriteTo(output, _map_mapBoolBool_codec); + mapStringString_.WriteTo(output, _map_mapStringString_codec); + mapStringBytes_.WriteTo(output, _map_mapStringBytes_codec); + mapStringNestedMessage_.WriteTo(output, _map_mapStringNestedMessage_codec); + mapStringForeignMessage_.WriteTo(output, _map_mapStringForeignMessage_codec); + mapStringNestedEnum_.WriteTo(output, _map_mapStringNestedEnum_codec); + mapStringForeignEnum_.WriteTo(output, _map_mapStringForeignEnum_codec); + if (oneofFieldCase_ == OneofFieldOneofCase.OneofUint32) { + output.WriteRawTag(248, 6); + output.WriteUInt32(OneofUint32); + } + if (oneofFieldCase_ == OneofFieldOneofCase.OneofNestedMessage) { + output.WriteRawTag(130, 7); + output.WriteMessage(OneofNestedMessage); + } + if (oneofFieldCase_ == OneofFieldOneofCase.OneofString) { + output.WriteRawTag(138, 7); + output.WriteString(OneofString); + } + if (oneofFieldCase_ == OneofFieldOneofCase.OneofBytes) { + output.WriteRawTag(146, 7); + output.WriteBytes(OneofBytes); + } + } + + public int CalculateSize() { + int size = 0; + if (OptionalInt32 != 0) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(OptionalInt32); + } + if (OptionalInt64 != 0L) { + size += 1 + pb::CodedOutputStream.ComputeInt64Size(OptionalInt64); + } + if (OptionalUint32 != 0) { + size += 1 + pb::CodedOutputStream.ComputeUInt32Size(OptionalUint32); + } + if (OptionalUint64 != 0UL) { + size += 1 + pb::CodedOutputStream.ComputeUInt64Size(OptionalUint64); + } + if (OptionalSint32 != 0) { + size += 1 + pb::CodedOutputStream.ComputeSInt32Size(OptionalSint32); + } + if (OptionalSint64 != 0L) { + size += 1 + pb::CodedOutputStream.ComputeSInt64Size(OptionalSint64); + } + if (OptionalFixed32 != 0) { + size += 1 + 4; + } + if (OptionalFixed64 != 0UL) { + size += 1 + 8; + } + if (OptionalSfixed32 != 0) { + size += 1 + 4; + } + if (OptionalSfixed64 != 0L) { + size += 1 + 8; + } + if (OptionalFloat != 0F) { + size += 1 + 4; + } + if (OptionalDouble != 0D) { + size += 1 + 8; + } + if (OptionalBool != false) { + size += 1 + 1; + } + if (OptionalString.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(OptionalString); + } + if (OptionalBytes.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeBytesSize(OptionalBytes); + } + if (optionalNestedMessage_ != null) { + size += 2 + pb::CodedOutputStream.ComputeMessageSize(OptionalNestedMessage); + } + if (optionalForeignMessage_ != null) { + size += 2 + pb::CodedOutputStream.ComputeMessageSize(OptionalForeignMessage); + } + if (OptionalNestedEnum != global::Conformance.TestAllTypes.Types.NestedEnum.FOO) { + size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) OptionalNestedEnum); + } + if (OptionalForeignEnum != global::Conformance.ForeignEnum.FOREIGN_FOO) { + size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) OptionalForeignEnum); + } + if (OptionalStringPiece.Length != 0) { + size += 2 + pb::CodedOutputStream.ComputeStringSize(OptionalStringPiece); + } + if (OptionalCord.Length != 0) { + size += 2 + pb::CodedOutputStream.ComputeStringSize(OptionalCord); + } + if (recursiveMessage_ != null) { + size += 2 + pb::CodedOutputStream.ComputeMessageSize(RecursiveMessage); + } + size += repeatedInt32_.CalculateSize(_repeated_repeatedInt32_codec); + size += repeatedInt64_.CalculateSize(_repeated_repeatedInt64_codec); + size += repeatedUint32_.CalculateSize(_repeated_repeatedUint32_codec); + size += repeatedUint64_.CalculateSize(_repeated_repeatedUint64_codec); + size += repeatedSint32_.CalculateSize(_repeated_repeatedSint32_codec); + size += repeatedSint64_.CalculateSize(_repeated_repeatedSint64_codec); + size += repeatedFixed32_.CalculateSize(_repeated_repeatedFixed32_codec); + size += repeatedFixed64_.CalculateSize(_repeated_repeatedFixed64_codec); + size += repeatedSfixed32_.CalculateSize(_repeated_repeatedSfixed32_codec); + size += repeatedSfixed64_.CalculateSize(_repeated_repeatedSfixed64_codec); + size += repeatedFloat_.CalculateSize(_repeated_repeatedFloat_codec); + size += repeatedDouble_.CalculateSize(_repeated_repeatedDouble_codec); + size += repeatedBool_.CalculateSize(_repeated_repeatedBool_codec); + size += repeatedString_.CalculateSize(_repeated_repeatedString_codec); + size += repeatedBytes_.CalculateSize(_repeated_repeatedBytes_codec); + size += repeatedNestedMessage_.CalculateSize(_repeated_repeatedNestedMessage_codec); + size += repeatedForeignMessage_.CalculateSize(_repeated_repeatedForeignMessage_codec); + size += repeatedNestedEnum_.CalculateSize(_repeated_repeatedNestedEnum_codec); + size += repeatedForeignEnum_.CalculateSize(_repeated_repeatedForeignEnum_codec); + size += repeatedStringPiece_.CalculateSize(_repeated_repeatedStringPiece_codec); + size += repeatedCord_.CalculateSize(_repeated_repeatedCord_codec); + size += mapInt32Int32_.CalculateSize(_map_mapInt32Int32_codec); + size += mapInt64Int64_.CalculateSize(_map_mapInt64Int64_codec); + size += mapUint32Uint32_.CalculateSize(_map_mapUint32Uint32_codec); + size += mapUint64Uint64_.CalculateSize(_map_mapUint64Uint64_codec); + size += mapSint32Sint32_.CalculateSize(_map_mapSint32Sint32_codec); + size += mapSint64Sint64_.CalculateSize(_map_mapSint64Sint64_codec); + size += mapFixed32Fixed32_.CalculateSize(_map_mapFixed32Fixed32_codec); + size += mapFixed64Fixed64_.CalculateSize(_map_mapFixed64Fixed64_codec); + size += mapSfixed32Sfixed32_.CalculateSize(_map_mapSfixed32Sfixed32_codec); + size += mapSfixed64Sfixed64_.CalculateSize(_map_mapSfixed64Sfixed64_codec); + size += mapInt32Float_.CalculateSize(_map_mapInt32Float_codec); + size += mapInt32Double_.CalculateSize(_map_mapInt32Double_codec); + size += mapBoolBool_.CalculateSize(_map_mapBoolBool_codec); + size += mapStringString_.CalculateSize(_map_mapStringString_codec); + size += mapStringBytes_.CalculateSize(_map_mapStringBytes_codec); + size += mapStringNestedMessage_.CalculateSize(_map_mapStringNestedMessage_codec); + size += mapStringForeignMessage_.CalculateSize(_map_mapStringForeignMessage_codec); + size += mapStringNestedEnum_.CalculateSize(_map_mapStringNestedEnum_codec); + size += mapStringForeignEnum_.CalculateSize(_map_mapStringForeignEnum_codec); + if (oneofFieldCase_ == OneofFieldOneofCase.OneofUint32) { + size += 2 + pb::CodedOutputStream.ComputeUInt32Size(OneofUint32); + } + if (oneofFieldCase_ == OneofFieldOneofCase.OneofNestedMessage) { + size += 2 + pb::CodedOutputStream.ComputeMessageSize(OneofNestedMessage); + } + if (oneofFieldCase_ == OneofFieldOneofCase.OneofString) { + size += 2 + pb::CodedOutputStream.ComputeStringSize(OneofString); + } + if (oneofFieldCase_ == OneofFieldOneofCase.OneofBytes) { + size += 2 + pb::CodedOutputStream.ComputeBytesSize(OneofBytes); + } + return size; + } + + public void MergeFrom(TestAllTypes other) { + if (other == null) { + return; + } + if (other.OptionalInt32 != 0) { + OptionalInt32 = other.OptionalInt32; + } + if (other.OptionalInt64 != 0L) { + OptionalInt64 = other.OptionalInt64; + } + if (other.OptionalUint32 != 0) { + OptionalUint32 = other.OptionalUint32; + } + if (other.OptionalUint64 != 0UL) { + OptionalUint64 = other.OptionalUint64; + } + if (other.OptionalSint32 != 0) { + OptionalSint32 = other.OptionalSint32; + } + if (other.OptionalSint64 != 0L) { + OptionalSint64 = other.OptionalSint64; + } + if (other.OptionalFixed32 != 0) { + OptionalFixed32 = other.OptionalFixed32; + } + if (other.OptionalFixed64 != 0UL) { + OptionalFixed64 = other.OptionalFixed64; + } + if (other.OptionalSfixed32 != 0) { + OptionalSfixed32 = other.OptionalSfixed32; + } + if (other.OptionalSfixed64 != 0L) { + OptionalSfixed64 = other.OptionalSfixed64; + } + if (other.OptionalFloat != 0F) { + OptionalFloat = other.OptionalFloat; + } + if (other.OptionalDouble != 0D) { + OptionalDouble = other.OptionalDouble; + } + if (other.OptionalBool != false) { + OptionalBool = other.OptionalBool; + } + if (other.OptionalString.Length != 0) { + OptionalString = other.OptionalString; + } + if (other.OptionalBytes.Length != 0) { + OptionalBytes = other.OptionalBytes; + } + if (other.optionalNestedMessage_ != null) { + if (optionalNestedMessage_ == null) { + optionalNestedMessage_ = new global::Conformance.TestAllTypes.Types.NestedMessage(); + } + OptionalNestedMessage.MergeFrom(other.OptionalNestedMessage); + } + if (other.optionalForeignMessage_ != null) { + if (optionalForeignMessage_ == null) { + optionalForeignMessage_ = new global::Conformance.ForeignMessage(); + } + OptionalForeignMessage.MergeFrom(other.OptionalForeignMessage); + } + if (other.OptionalNestedEnum != global::Conformance.TestAllTypes.Types.NestedEnum.FOO) { + OptionalNestedEnum = other.OptionalNestedEnum; + } + if (other.OptionalForeignEnum != global::Conformance.ForeignEnum.FOREIGN_FOO) { + OptionalForeignEnum = other.OptionalForeignEnum; + } + if (other.OptionalStringPiece.Length != 0) { + OptionalStringPiece = other.OptionalStringPiece; + } + if (other.OptionalCord.Length != 0) { + OptionalCord = other.OptionalCord; + } + if (other.recursiveMessage_ != null) { + if (recursiveMessage_ == null) { + recursiveMessage_ = new global::Conformance.TestAllTypes(); + } + RecursiveMessage.MergeFrom(other.RecursiveMessage); + } + repeatedInt32_.Add(other.repeatedInt32_); + repeatedInt64_.Add(other.repeatedInt64_); + repeatedUint32_.Add(other.repeatedUint32_); + repeatedUint64_.Add(other.repeatedUint64_); + repeatedSint32_.Add(other.repeatedSint32_); + repeatedSint64_.Add(other.repeatedSint64_); + repeatedFixed32_.Add(other.repeatedFixed32_); + repeatedFixed64_.Add(other.repeatedFixed64_); + repeatedSfixed32_.Add(other.repeatedSfixed32_); + repeatedSfixed64_.Add(other.repeatedSfixed64_); + repeatedFloat_.Add(other.repeatedFloat_); + repeatedDouble_.Add(other.repeatedDouble_); + repeatedBool_.Add(other.repeatedBool_); + repeatedString_.Add(other.repeatedString_); + repeatedBytes_.Add(other.repeatedBytes_); + repeatedNestedMessage_.Add(other.repeatedNestedMessage_); + repeatedForeignMessage_.Add(other.repeatedForeignMessage_); + repeatedNestedEnum_.Add(other.repeatedNestedEnum_); + repeatedForeignEnum_.Add(other.repeatedForeignEnum_); + repeatedStringPiece_.Add(other.repeatedStringPiece_); + repeatedCord_.Add(other.repeatedCord_); + mapInt32Int32_.Add(other.mapInt32Int32_); + mapInt64Int64_.Add(other.mapInt64Int64_); + mapUint32Uint32_.Add(other.mapUint32Uint32_); + mapUint64Uint64_.Add(other.mapUint64Uint64_); + mapSint32Sint32_.Add(other.mapSint32Sint32_); + mapSint64Sint64_.Add(other.mapSint64Sint64_); + mapFixed32Fixed32_.Add(other.mapFixed32Fixed32_); + mapFixed64Fixed64_.Add(other.mapFixed64Fixed64_); + mapSfixed32Sfixed32_.Add(other.mapSfixed32Sfixed32_); + mapSfixed64Sfixed64_.Add(other.mapSfixed64Sfixed64_); + mapInt32Float_.Add(other.mapInt32Float_); + mapInt32Double_.Add(other.mapInt32Double_); + mapBoolBool_.Add(other.mapBoolBool_); + mapStringString_.Add(other.mapStringString_); + mapStringBytes_.Add(other.mapStringBytes_); + mapStringNestedMessage_.Add(other.mapStringNestedMessage_); + mapStringForeignMessage_.Add(other.mapStringForeignMessage_); + mapStringNestedEnum_.Add(other.mapStringNestedEnum_); + mapStringForeignEnum_.Add(other.mapStringForeignEnum_); + switch (other.OneofFieldCase) { + case OneofFieldOneofCase.OneofUint32: + OneofUint32 = other.OneofUint32; + break; + case OneofFieldOneofCase.OneofNestedMessage: + OneofNestedMessage = other.OneofNestedMessage; + break; + case OneofFieldOneofCase.OneofString: + OneofString = other.OneofString; + break; + case OneofFieldOneofCase.OneofBytes: + OneofBytes = other.OneofBytes; + break; + } + + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 8: { + OptionalInt32 = input.ReadInt32(); + break; + } + case 16: { + OptionalInt64 = input.ReadInt64(); + break; + } + case 24: { + OptionalUint32 = input.ReadUInt32(); + break; + } + case 32: { + OptionalUint64 = input.ReadUInt64(); + break; + } + case 40: { + OptionalSint32 = input.ReadSInt32(); + break; + } + case 48: { + OptionalSint64 = input.ReadSInt64(); + break; + } + case 61: { + OptionalFixed32 = input.ReadFixed32(); + break; + } + case 65: { + OptionalFixed64 = input.ReadFixed64(); + break; + } + case 77: { + OptionalSfixed32 = input.ReadSFixed32(); + break; + } + case 81: { + OptionalSfixed64 = input.ReadSFixed64(); + break; + } + case 93: { + OptionalFloat = input.ReadFloat(); + break; + } + case 97: { + OptionalDouble = input.ReadDouble(); + break; + } + case 104: { + OptionalBool = input.ReadBool(); + break; + } + case 114: { + OptionalString = input.ReadString(); + break; + } + case 122: { + OptionalBytes = input.ReadBytes(); + break; + } + case 146: { + if (optionalNestedMessage_ == null) { + optionalNestedMessage_ = new global::Conformance.TestAllTypes.Types.NestedMessage(); + } + input.ReadMessage(optionalNestedMessage_); + break; + } + case 154: { + if (optionalForeignMessage_ == null) { + optionalForeignMessage_ = new global::Conformance.ForeignMessage(); + } + input.ReadMessage(optionalForeignMessage_); + break; + } + case 168: { + optionalNestedEnum_ = (global::Conformance.TestAllTypes.Types.NestedEnum) input.ReadEnum(); + break; + } + case 176: { + optionalForeignEnum_ = (global::Conformance.ForeignEnum) input.ReadEnum(); + break; + } + case 194: { + OptionalStringPiece = input.ReadString(); + break; + } + case 202: { + OptionalCord = input.ReadString(); + break; + } + case 218: { + if (recursiveMessage_ == null) { + recursiveMessage_ = new global::Conformance.TestAllTypes(); + } + input.ReadMessage(recursiveMessage_); + break; + } + case 250: + case 248: { + repeatedInt32_.AddEntriesFrom(input, _repeated_repeatedInt32_codec); + break; + } + case 258: + case 256: { + repeatedInt64_.AddEntriesFrom(input, _repeated_repeatedInt64_codec); + break; + } + case 266: + case 264: { + repeatedUint32_.AddEntriesFrom(input, _repeated_repeatedUint32_codec); + break; + } + case 274: + case 272: { + repeatedUint64_.AddEntriesFrom(input, _repeated_repeatedUint64_codec); + break; + } + case 282: + case 280: { + repeatedSint32_.AddEntriesFrom(input, _repeated_repeatedSint32_codec); + break; + } + case 290: + case 288: { + repeatedSint64_.AddEntriesFrom(input, _repeated_repeatedSint64_codec); + break; + } + case 298: + case 301: { + repeatedFixed32_.AddEntriesFrom(input, _repeated_repeatedFixed32_codec); + break; + } + case 306: + case 305: { + repeatedFixed64_.AddEntriesFrom(input, _repeated_repeatedFixed64_codec); + break; + } + case 314: + case 317: { + repeatedSfixed32_.AddEntriesFrom(input, _repeated_repeatedSfixed32_codec); + break; + } + case 322: + case 321: { + repeatedSfixed64_.AddEntriesFrom(input, _repeated_repeatedSfixed64_codec); + break; + } + case 330: + case 333: { + repeatedFloat_.AddEntriesFrom(input, _repeated_repeatedFloat_codec); + break; + } + case 338: + case 337: { + repeatedDouble_.AddEntriesFrom(input, _repeated_repeatedDouble_codec); + break; + } + case 346: + case 344: { + repeatedBool_.AddEntriesFrom(input, _repeated_repeatedBool_codec); + break; + } + case 354: { + repeatedString_.AddEntriesFrom(input, _repeated_repeatedString_codec); + break; + } + case 362: { + repeatedBytes_.AddEntriesFrom(input, _repeated_repeatedBytes_codec); + break; + } + case 386: { + repeatedNestedMessage_.AddEntriesFrom(input, _repeated_repeatedNestedMessage_codec); + break; + } + case 394: { + repeatedForeignMessage_.AddEntriesFrom(input, _repeated_repeatedForeignMessage_codec); + break; + } + case 410: + case 408: { + repeatedNestedEnum_.AddEntriesFrom(input, _repeated_repeatedNestedEnum_codec); + break; + } + case 418: + case 416: { + repeatedForeignEnum_.AddEntriesFrom(input, _repeated_repeatedForeignEnum_codec); + break; + } + case 434: { + repeatedStringPiece_.AddEntriesFrom(input, _repeated_repeatedStringPiece_codec); + break; + } + case 442: { + repeatedCord_.AddEntriesFrom(input, _repeated_repeatedCord_codec); + break; + } + case 450: { + mapInt32Int32_.AddEntriesFrom(input, _map_mapInt32Int32_codec); + break; + } + case 458: { + mapInt64Int64_.AddEntriesFrom(input, _map_mapInt64Int64_codec); + break; + } + case 466: { + mapUint32Uint32_.AddEntriesFrom(input, _map_mapUint32Uint32_codec); + break; + } + case 474: { + mapUint64Uint64_.AddEntriesFrom(input, _map_mapUint64Uint64_codec); + break; + } + case 482: { + mapSint32Sint32_.AddEntriesFrom(input, _map_mapSint32Sint32_codec); + break; + } + case 490: { + mapSint64Sint64_.AddEntriesFrom(input, _map_mapSint64Sint64_codec); + break; + } + case 498: { + mapFixed32Fixed32_.AddEntriesFrom(input, _map_mapFixed32Fixed32_codec); + break; + } + case 506: { + mapFixed64Fixed64_.AddEntriesFrom(input, _map_mapFixed64Fixed64_codec); + break; + } + case 514: { + mapSfixed32Sfixed32_.AddEntriesFrom(input, _map_mapSfixed32Sfixed32_codec); + break; + } + case 522: { + mapSfixed64Sfixed64_.AddEntriesFrom(input, _map_mapSfixed64Sfixed64_codec); + break; + } + case 530: { + mapInt32Float_.AddEntriesFrom(input, _map_mapInt32Float_codec); + break; + } + case 538: { + mapInt32Double_.AddEntriesFrom(input, _map_mapInt32Double_codec); + break; + } + case 546: { + mapBoolBool_.AddEntriesFrom(input, _map_mapBoolBool_codec); + break; + } + case 554: { + mapStringString_.AddEntriesFrom(input, _map_mapStringString_codec); + break; + } + case 562: { + mapStringBytes_.AddEntriesFrom(input, _map_mapStringBytes_codec); + break; + } + case 570: { + mapStringNestedMessage_.AddEntriesFrom(input, _map_mapStringNestedMessage_codec); + break; + } + case 578: { + mapStringForeignMessage_.AddEntriesFrom(input, _map_mapStringForeignMessage_codec); + break; + } + case 586: { + mapStringNestedEnum_.AddEntriesFrom(input, _map_mapStringNestedEnum_codec); + break; + } + case 594: { + mapStringForeignEnum_.AddEntriesFrom(input, _map_mapStringForeignEnum_codec); + break; + } + case 888: { + OneofUint32 = input.ReadUInt32(); + break; + } + case 898: { + global::Conformance.TestAllTypes.Types.NestedMessage subBuilder = new global::Conformance.TestAllTypes.Types.NestedMessage(); + if (oneofFieldCase_ == OneofFieldOneofCase.OneofNestedMessage) { + subBuilder.MergeFrom(OneofNestedMessage); + } + input.ReadMessage(subBuilder); + OneofNestedMessage = subBuilder; + break; + } + case 906: { + OneofString = input.ReadString(); + break; + } + case 914: { + OneofBytes = input.ReadBytes(); + break; + } + } + } + } + + #region Nested types + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public static partial class Types { + public enum NestedEnum { + FOO = 0, + BAR = 1, + BAZ = 2, + NEG = -1, + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public sealed partial class NestedMessage : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new NestedMessage()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Conformance.TestAllTypes.Descriptor.NestedTypes[0]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public NestedMessage() { + OnConstruction(); + } + + partial void OnConstruction(); + + public NestedMessage(NestedMessage other) : this() { + a_ = other.a_; + Corecursive = other.corecursive_ != null ? other.Corecursive.Clone() : null; + } + + public NestedMessage Clone() { + return new NestedMessage(this); + } + + public const int AFieldNumber = 1; + private int a_; + public int A { + get { return a_; } + set { + a_ = value; + } + } + + public const int CorecursiveFieldNumber = 2; + private global::Conformance.TestAllTypes corecursive_; + public global::Conformance.TestAllTypes Corecursive { + get { return corecursive_; } + set { + corecursive_ = value; + } + } + + public override bool Equals(object other) { + return Equals(other as NestedMessage); + } + + public bool Equals(NestedMessage other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (A != other.A) return false; + if (!object.Equals(Corecursive, other.Corecursive)) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (A != 0) hash ^= A.GetHashCode(); + if (corecursive_ != null) hash ^= Corecursive.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (A != 0) { + output.WriteRawTag(8); + output.WriteInt32(A); + } + if (corecursive_ != null) { + output.WriteRawTag(18); + output.WriteMessage(Corecursive); + } + } + + public int CalculateSize() { + int size = 0; + if (A != 0) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(A); + } + if (corecursive_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Corecursive); + } + return size; + } + + public void MergeFrom(NestedMessage other) { + if (other == null) { + return; + } + if (other.A != 0) { + A = other.A; + } + if (other.corecursive_ != null) { + if (corecursive_ == null) { + corecursive_ = new global::Conformance.TestAllTypes(); + } + Corecursive.MergeFrom(other.Corecursive); + } + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 8: { + A = input.ReadInt32(); + break; + } + case 18: { + if (corecursive_ == null) { + corecursive_ = new global::Conformance.TestAllTypes(); + } + input.ReadMessage(corecursive_); + break; + } + } + } + } + + } + + } + #endregion + + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public sealed partial class ForeignMessage : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new ForeignMessage()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Conformance.Conformance.Descriptor.MessageTypes[3]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public ForeignMessage() { + OnConstruction(); + } + + partial void OnConstruction(); + + public ForeignMessage(ForeignMessage other) : this() { + c_ = other.c_; + } + + public ForeignMessage Clone() { + return new ForeignMessage(this); + } + + public const int CFieldNumber = 1; + private int c_; + public int C { + get { return c_; } + set { + c_ = value; + } + } + + public override bool Equals(object other) { + return Equals(other as ForeignMessage); + } + + public bool Equals(ForeignMessage other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (C != other.C) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (C != 0) hash ^= C.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (C != 0) { + output.WriteRawTag(8); + output.WriteInt32(C); + } + } + + public int CalculateSize() { + int size = 0; + if (C != 0) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(C); + } + return size; + } + + public void MergeFrom(ForeignMessage other) { + if (other == null) { + return; + } + if (other.C != 0) { + C = other.C; + } + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 8: { + C = input.ReadInt32(); + break; + } + } + } + } + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/src/ProtoMunge/ProtoMunge.csproj b/csharp/src/Google.Protobuf.Conformance/Google.Protobuf.Conformance.csproj similarity index 54% rename from csharp/src/ProtoMunge/ProtoMunge.csproj rename to csharp/src/Google.Protobuf.Conformance/Google.Protobuf.Conformance.csproj index 60c907b188a9f..82f728d192947 100644 --- a/csharp/src/ProtoMunge/ProtoMunge.csproj +++ b/csharp/src/Google.Protobuf.Conformance/Google.Protobuf.Conformance.csproj @@ -1,67 +1,61 @@ - - - - CLIENTPROFILE - NET35 - Debug - AnyCPU - 9.0.30729 - 2.0 - {8F09AF72-3327-4FA7-BC09-070B80221AB9} - Exe - Properties - Google.ProtocolBuffers.ProtoMunge - ProtoMunge - v4.0 - 512 - Client - - - true - full - false - bin\Debug - obj\Debug\ - DEBUG;TRACE - prompt - 4 - true - Off - - - pdbonly - true - bin\Release - obj\Release\ - TRACE - prompt - 4 - true - Off - - - - - - - - - - - - {6908BDCE-D925-43F3-94AC-A531E6DF2591} - ProtocolBuffers - - - - - - - + + + + + Debug + AnyCPU + {0607D1B8-80D6-4B35-9857-1263C1B32B94} + Exe + Properties + Google.Protobuf.Conformance + Google.Protobuf.Conformance + v4.5 + 512 + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + {6908bdce-d925-43f3-94ac-a531e6df2591} + Google.Protobuf + + + + \ No newline at end of file diff --git a/csharp/src/Google.Protobuf.Conformance/Program.cs b/csharp/src/Google.Protobuf.Conformance/Program.cs new file mode 100644 index 0000000000000..af92da9f37c49 --- /dev/null +++ b/csharp/src/Google.Protobuf.Conformance/Program.cs @@ -0,0 +1,126 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using Conformance; +using System; +using System.IO; + +namespace Google.Protobuf.Conformance +{ + /// + /// Conformance tests. The test runner will provide JSON or proto data on stdin, + /// and this program will produce its output on stdout. + /// + class Program + { + private static void Main(string[] args) + { + // This way we get the binary streams instead of readers/writers. + var input = new BinaryReader(Console.OpenStandardInput()); + var output = new BinaryWriter(Console.OpenStandardOutput()); + + int count = 0; + while (RunTest(input, output)) + { + count++; + } + Console.Error.WriteLine("Received EOF after {0} tests", count); + } + + private static bool RunTest(BinaryReader input, BinaryWriter output) + { + int? size = ReadInt32(input); + if (size == null) + { + return false; + } + byte[] inputData = input.ReadBytes(size.Value); + if (inputData.Length != size.Value) + { + throw new EndOfStreamException("Read " + inputData.Length + " bytes of data when expecting " + size); + } + ConformanceRequest request = ConformanceRequest.Parser.ParseFrom(inputData); + ConformanceResponse response = PerformRequest(request); + byte[] outputData = response.ToByteArray(); + output.Write(outputData.Length); + output.Write(outputData); + // Ready for another test... + return true; + } + + private static ConformanceResponse PerformRequest(ConformanceRequest request) + { + TestAllTypes message; + switch (request.PayloadCase) + { + case ConformanceRequest.PayloadOneofCase.JsonPayload: + return new ConformanceResponse { Skipped = "JSON parsing not implemented in C# yet" }; + case ConformanceRequest.PayloadOneofCase.ProtobufPayload: + try + { + message = TestAllTypes.Parser.ParseFrom(request.ProtobufPayload); + } + catch (InvalidProtocolBufferException e) + { + return new ConformanceResponse { ParseError = e.Message }; + } + break; + default: + throw new Exception("Unsupported request payload: " + request.PayloadCase); + } + switch (request.RequestedOutputFormat) + { + case global::Conformance.WireFormat.JSON: + return new ConformanceResponse { JsonPayload = JsonFormatter.Default.Format(message) }; + case global::Conformance.WireFormat.PROTOBUF: + return new ConformanceResponse { ProtobufPayload = message.ToByteString() }; + default: + throw new Exception("Unsupported request output format: " + request.PayloadCase); + } + } + + private static int? ReadInt32(BinaryReader input) + { + byte[] bytes = input.ReadBytes(4); + if (bytes.Length == 0) + { + // Cleanly reached the end of the stream + return null; + } + if (bytes.Length != 4) + { + throw new EndOfStreamException("Read " + bytes.Length + " bytes of size when expecting 4"); + } + return bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24); + } + } +} diff --git a/csharp/src/ProtocolBuffers.Serialization/Properties/AssemblyInfo.cs b/csharp/src/Google.Protobuf.Conformance/Properties/AssemblyInfo.cs similarity index 67% rename from csharp/src/ProtocolBuffers.Serialization/Properties/AssemblyInfo.cs rename to csharp/src/Google.Protobuf.Conformance/Properties/AssemblyInfo.cs index 0ab5812041d18..d22e90fd8f264 100644 --- a/csharp/src/ProtocolBuffers.Serialization/Properties/AssemblyInfo.cs +++ b/csharp/src/Google.Protobuf.Conformance/Properties/AssemblyInfo.cs @@ -1,65 +1,48 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -using System; -using System.Reflection; -using System.Runtime.InteropServices; -using System.Runtime.CompilerServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. - -[assembly: AssemblyTitle("ProtocolBuffers")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("ProtocolBuffers")] -[assembly: AssemblyCopyright("Copyright © 2008")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("2.4.1.555")] - -[assembly: AssemblyVersion("2.4.1.555")] - -#if !NOFILEVERSION -[assembly: AssemblyFileVersion("2.4.1.555")] -#endif +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using System.Reflection; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Google.Protobuf.Conformance")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Google.Protobuf.Conformance")] +[assembly: AssemblyCopyright("Copyright © 2015")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +[assembly: AssemblyVersion("3.0.0.0")] +[assembly: AssemblyFileVersion("3.0.0.0")] diff --git a/csharp/src/ProtoDump/ProtoDump.csproj b/csharp/src/Google.Protobuf.JsonDump/Google.Protobuf.JsonDump.csproj similarity index 82% rename from csharp/src/ProtoDump/ProtoDump.csproj rename to csharp/src/Google.Protobuf.JsonDump/Google.Protobuf.JsonDump.csproj index b7e6c1a338c43..ede1f7781c3f4 100644 --- a/csharp/src/ProtoDump/ProtoDump.csproj +++ b/csharp/src/Google.Protobuf.JsonDump/Google.Protobuf.JsonDump.csproj @@ -1,8 +1,6 @@  - CLIENTPROFILE - NET35 Debug AnyCPU 9.0.30729 @@ -10,11 +8,12 @@ {D7282E99-2DC3-405B-946F-177DB2FD2AE2} Exe Properties - Google.ProtocolBuffers.ProtoDump - ProtoDump - v4.0 + Google.Protobuf.JsonDump + Google.Protobuf.JsonDump + v4.5 512 - Client + + true @@ -27,6 +26,7 @@ 4 true Off + false pdbonly @@ -38,6 +38,7 @@ 4 true Off + false @@ -48,9 +49,9 @@ - + {6908BDCE-D925-43F3-94AC-A531E6DF2591} - ProtocolBuffers + Google.Protobuf diff --git a/csharp/src/ProtoDump/Program.cs b/csharp/src/Google.Protobuf.JsonDump/Program.cs similarity index 61% rename from csharp/src/ProtoDump/Program.cs rename to csharp/src/Google.Protobuf.JsonDump/Program.cs index a935e7807bae6..99e60e901a2fa 100644 --- a/csharp/src/ProtoDump/Program.cs +++ b/csharp/src/Google.Protobuf.JsonDump/Program.cs @@ -1,10 +1,7 @@ #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/ +// 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 @@ -31,16 +28,15 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - #endregion using System; using System.IO; -namespace Google.ProtocolBuffers.ProtoDump +namespace Google.Protobuf.ProtoDump { /// - /// Small utility to load a binary message and dump it in text form + /// Small utility to load a binary message and dump it in JSON format. /// internal class Program { @@ -48,41 +44,29 @@ private static int Main(string[] args) { if (args.Length != 2) { - Console.Error.WriteLine("Usage: ProtoDump "); + Console.Error.WriteLine("Usage: Google.Protobuf.JsonDump "); Console.Error.WriteLine("The descriptor type name is the fully-qualified message name,"); Console.Error.WriteLine("including assembly e.g. ProjectNamespace.Message,Company.Project"); return 1; } - IMessage defaultMessage; - try - { - defaultMessage = MessageUtil.GetDefaultMessage(args[0]); - } - catch (ArgumentException e) + Type type = Type.GetType(args[0]); + if (type == null) { - Console.Error.WriteLine(e.Message); + Console.Error.WriteLine("Unable to load type {0}.", args[0]); return 1; } - try + if (!typeof(IMessage).IsAssignableFrom(type)) { - IBuilder builder = defaultMessage.WeakCreateBuilderForType(); - if (builder == null) - { - Console.Error.WriteLine("Unable to create builder"); - return 1; - } - byte[] inputData = File.ReadAllBytes(args[1]); - builder.WeakMergeFrom(ByteString.CopyFrom(inputData)); - Console.WriteLine(TextFormat.PrintToString(builder.WeakBuild())); - return 0; + Console.Error.WriteLine("Type {0} doesn't implement IMessage.", args[0]); + return 1; } - catch (Exception e) + IMessage message = (IMessage) Activator.CreateInstance(type); + using (var input = File.OpenRead(args[1])) { - Console.Error.WriteLine("Error: {0}", e.Message); - Console.Error.WriteLine(); - Console.Error.WriteLine("Detailed exception information: {0}", e); - return 1; + message.MergeFrom(input); } + Console.WriteLine(message); + return 0; } } } \ No newline at end of file diff --git a/csharp/src/ProtoDump/Properties/AssemblyInfo.cs b/csharp/src/Google.Protobuf.JsonDump/Properties/AssemblyInfo.cs similarity index 52% rename from csharp/src/ProtoDump/Properties/AssemblyInfo.cs rename to csharp/src/Google.Protobuf.JsonDump/Properties/AssemblyInfo.cs index a8ce8eaef8713..d980b0139319b 100644 --- a/csharp/src/ProtoDump/Properties/AssemblyInfo.cs +++ b/csharp/src/Google.Protobuf.JsonDump/Properties/AssemblyInfo.cs @@ -11,20 +11,9 @@ [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ProtoDump")] -[assembly: AssemblyCopyright("Copyright © 2009")] +[assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("2.4.1.555")] - -[assembly: AssemblyVersion("2.4.1.555")] -[assembly: AssemblyFileVersion("2.4.1.555")] \ No newline at end of file +[assembly: AssemblyVersion("3.0.0.0")] +[assembly: AssemblyFileVersion("3.0.0.0")] diff --git a/csharp/src/ProtoBench/app.config b/csharp/src/Google.Protobuf.JsonDump/app.config similarity index 68% rename from csharp/src/ProtoBench/app.config rename to csharp/src/Google.Protobuf.JsonDump/app.config index e2a5a1876245c..51278a456315e 100644 --- a/csharp/src/ProtoBench/app.config +++ b/csharp/src/Google.Protobuf.JsonDump/app.config @@ -1,3 +1,3 @@ - + diff --git a/csharp/src/ProtocolBuffers.Test/ByteStringTest.cs b/csharp/src/Google.Protobuf.Test/ByteStringTest.cs similarity index 77% rename from csharp/src/ProtocolBuffers.Test/ByteStringTest.cs rename to csharp/src/Google.Protobuf.Test/ByteStringTest.cs index e4f7bd9e66e6b..685e130a748c9 100644 --- a/csharp/src/ProtocolBuffers.Test/ByteStringTest.cs +++ b/csharp/src/Google.Protobuf.Test/ByteStringTest.cs @@ -1,10 +1,7 @@ #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/ +// 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 @@ -31,17 +28,44 @@ // 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.Text; using NUnit.Framework; -namespace Google.ProtocolBuffers +namespace Google.Protobuf { public class ByteStringTest { + [Test] + public void Equality() + { + ByteString b1 = ByteString.CopyFrom(1, 2, 3); + ByteString b2 = ByteString.CopyFrom(1, 2, 3); + ByteString b3 = ByteString.CopyFrom(1, 2, 4); + ByteString b4 = ByteString.CopyFrom(1, 2, 3, 4); + EqualityTester.AssertEquality(b1, b1); + EqualityTester.AssertEquality(b1, b2); + EqualityTester.AssertInequality(b1, b3); + EqualityTester.AssertInequality(b1, b4); + EqualityTester.AssertInequality(b1, null); +#pragma warning disable 1718 // Deliberately calling ==(b1, b1) and !=(b1, b1) + Assert.IsTrue(b1 == b1); + Assert.IsTrue(b1 == b2); + Assert.IsFalse(b1 == b3); + Assert.IsFalse(b1 == b4); + Assert.IsFalse(b1 == null); + Assert.IsTrue((ByteString) null == null); + Assert.IsFalse(b1 != b1); + Assert.IsFalse(b1 != b2); +#pragma warning disable 1718 + Assert.IsTrue(b1 != b3); + Assert.IsTrue(b1 != b4); + Assert.IsTrue(b1 != null); + Assert.IsFalse((ByteString) null != null); + } + [Test] public void EmptyByteStringHasZeroSize() { diff --git a/csharp/src/Google.Protobuf.Test/CodedInputStreamExtensions.cs b/csharp/src/Google.Protobuf.Test/CodedInputStreamExtensions.cs new file mode 100644 index 0000000000000..23af28870ab4b --- /dev/null +++ b/csharp/src/Google.Protobuf.Test/CodedInputStreamExtensions.cs @@ -0,0 +1,53 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using NUnit.Framework; + +namespace Google.Protobuf +{ + internal static class CodedInputStreamExtensions + { + public static void AssertNextTag(this CodedInputStream input, uint expectedTag) + { + uint tag = input.ReadTag(); + Assert.AreEqual(expectedTag, tag); + } + + public static T ReadMessage(this CodedInputStream stream, MessageParser parser) + where T : IMessage + { + var message = parser.CreateTemplate(); + stream.ReadMessage(message); + return message; + } + } +} diff --git a/csharp/src/ProtocolBuffers.Test/CodedInputStreamTest.cs b/csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs similarity index 61% rename from csharp/src/ProtocolBuffers.Test/CodedInputStreamTest.cs rename to csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs index 9bb8ba27a81c7..54c44e47767f5 100644 --- a/csharp/src/ProtocolBuffers.Test/CodedInputStreamTest.cs +++ b/csharp/src/Google.Protobuf.Test/CodedInputStreamTest.cs @@ -1,10 +1,7 @@ #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/ +// 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 @@ -31,17 +28,14 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - #endregion using System; -using System.Collections.Generic; using System.IO; -using Google.ProtocolBuffers.Descriptors; -using Google.ProtocolBuffers.TestProtos; +using Google.Protobuf.TestProtos; using NUnit.Framework; -namespace Google.ProtocolBuffers +namespace Google.Protobuf { public class CodedInputStreamTest { @@ -61,24 +55,24 @@ private static byte[] Bytes(params int[] bytesAsInts) } /// - /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() and + /// Parses the given bytes using ReadRawVarint32() and ReadRawVarint64() /// private static void AssertReadVarint(byte[] data, ulong value) { - CodedInputStream input = CodedInputStream.CreateInstance(data); + CodedInputStream input = new CodedInputStream(data); Assert.AreEqual((uint) value, input.ReadRawVarint32()); - input = CodedInputStream.CreateInstance(data); + input = new CodedInputStream(data); Assert.AreEqual(value, input.ReadRawVarint64()); Assert.IsTrue(input.IsAtEnd); // Try different block sizes. for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2) { - input = CodedInputStream.CreateInstance(new SmallBlockInputStream(data, bufferSize)); + input = new CodedInputStream(new SmallBlockInputStream(data, bufferSize)); Assert.AreEqual((uint) value, input.ReadRawVarint32()); - input = CodedInputStream.CreateInstance(new SmallBlockInputStream(data, bufferSize)); + input = new CodedInputStream(new SmallBlockInputStream(data, bufferSize)); Assert.AreEqual(value, input.ReadRawVarint64()); Assert.IsTrue(input.IsAtEnd); } @@ -101,11 +95,11 @@ private static void AssertReadVarint(byte[] data, ulong value) /// private static void AssertReadVarintFailure(InvalidProtocolBufferException expected, byte[] data) { - CodedInputStream input = CodedInputStream.CreateInstance(data); + CodedInputStream input = new CodedInputStream(data); var exception = Assert.Throws(() => input.ReadRawVarint32()); Assert.AreEqual(expected.Message, exception.Message); - input = CodedInputStream.CreateInstance(data); + input = new CodedInputStream(data); exception = Assert.Throws(() => input.ReadRawVarint64()); Assert.AreEqual(expected.Message, exception.Message); @@ -158,14 +152,14 @@ public void ReadVarint() /// private static void AssertReadLittleEndian32(byte[] data, uint value) { - CodedInputStream input = CodedInputStream.CreateInstance(data); + CodedInputStream input = new CodedInputStream(data); Assert.AreEqual(value, input.ReadRawLittleEndian32()); Assert.IsTrue(input.IsAtEnd); // Try different block sizes. for (int blockSize = 1; blockSize <= 16; blockSize *= 2) { - input = CodedInputStream.CreateInstance( + input = new CodedInputStream( new SmallBlockInputStream(data, blockSize)); Assert.AreEqual(value, input.ReadRawLittleEndian32()); Assert.IsTrue(input.IsAtEnd); @@ -178,14 +172,14 @@ private static void AssertReadLittleEndian32(byte[] data, uint value) /// private static void AssertReadLittleEndian64(byte[] data, ulong value) { - CodedInputStream input = CodedInputStream.CreateInstance(data); + CodedInputStream input = new CodedInputStream(data); Assert.AreEqual(value, input.ReadRawLittleEndian64()); Assert.IsTrue(input.IsAtEnd); // Try different block sizes. for (int blockSize = 1; blockSize <= 16; blockSize *= 2) { - input = CodedInputStream.CreateInstance( + input = new CodedInputStream( new SmallBlockInputStream(data, blockSize)); Assert.AreEqual(value, input.ReadRawLittleEndian64()); Assert.IsTrue(input.IsAtEnd); @@ -231,66 +225,26 @@ public void DecodeZigZag64() Assert.AreEqual(0x7FFFFFFFFFFFFFFFL, CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFEL)); Assert.AreEqual(unchecked((long) 0x8000000000000000L), CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFFL)); } - + [Test] - public void ReadWholeMessage() + public void ReadWholeMessage_VaryingBlockSizes() { - TestAllTypes message = TestUtil.GetAllSet(); + TestAllTypes message = SampleMessages.CreateFullTestAllTypes(); byte[] rawBytes = message.ToByteArray(); - Assert.AreEqual(rawBytes.Length, message.SerializedSize); - TestAllTypes message2 = TestAllTypes.ParseFrom(rawBytes); - TestUtil.AssertAllFieldsSet(message2); + Assert.AreEqual(rawBytes.Length, message.CalculateSize()); + TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(rawBytes); + Assert.AreEqual(message, message2); // Try different block sizes. for (int blockSize = 1; blockSize < 256; blockSize *= 2) { - message2 = TestAllTypes.ParseFrom(new SmallBlockInputStream(rawBytes, blockSize)); - TestUtil.AssertAllFieldsSet(message2); - } - } - - [Test] - public void SkipWholeMessage() - { - TestAllTypes message = TestUtil.GetAllSet(); - byte[] rawBytes = message.ToByteArray(); - - // Create two parallel inputs. Parse one as unknown fields while using - // skipField() to skip each field on the other. Expect the same tags. - CodedInputStream input1 = CodedInputStream.CreateInstance(rawBytes); - CodedInputStream input2 = CodedInputStream.CreateInstance(rawBytes); - UnknownFieldSet.Builder unknownFields = UnknownFieldSet.CreateBuilder(); - - uint tag; - string name; - while (input1.ReadTag(out tag, out name)) - { - uint tag2; - Assert.IsTrue(input2.ReadTag(out tag2, out name)); - Assert.AreEqual(tag, tag2); - - unknownFields.MergeFieldFrom(tag, input1); - input2.SkipField(); + message2 = TestAllTypes.Parser.ParseFrom(new SmallBlockInputStream(rawBytes, blockSize)); + Assert.AreEqual(message, message2); } } - - /// - /// Test that a bug in SkipRawBytes has been fixed: if the skip - /// skips exactly up to a limit, this should bnot break things - /// + [Test] - public void SkipRawBytesBug() - { - byte[] rawBytes = new byte[] {1, 2}; - CodedInputStream input = CodedInputStream.CreateInstance(rawBytes); - - int limit = input.PushLimit(1); - input.SkipRawBytes(1); - input.PopLimit(limit); - Assert.AreEqual(2, input.ReadRawByte()); - } - public void ReadHugeBlob() { // Allocate and initialize a 1MB blob. @@ -301,30 +255,21 @@ public void ReadHugeBlob() } // Make a message containing it. - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - TestUtil.SetAllFields(builder); - builder.SetOptionalBytes(ByteString.CopyFrom(blob)); - TestAllTypes message = builder.Build(); + var message = new TestAllTypes { SingleBytes = ByteString.CopyFrom(blob) }; // Serialize and parse it. Make sure to parse from an InputStream, not // directly from a ByteString, so that CodedInputStream uses buffered // reading. - TestAllTypes message2 = TestAllTypes.ParseFrom(message.ToByteString().CreateCodedInput()); + TestAllTypes message2 = TestAllTypes.Parser.ParseFrom(message.ToByteString()); - Assert.AreEqual(message.OptionalBytes, message2.OptionalBytes); - - // Make sure all the other fields were parsed correctly. - TestAllTypes message3 = TestAllTypes.CreateBuilder(message2) - .SetOptionalBytes(TestUtil.GetAllSet().OptionalBytes) - .Build(); - TestUtil.AssertAllFieldsSet(message3); + Assert.AreEqual(message, message2); } [Test] public void ReadMaliciouslyLargeBlob() { MemoryStream ms = new MemoryStream(); - CodedOutputStream output = CodedOutputStream.CreateInstance(ms); + CodedOutputStream output = new CodedOutputStream(ms); uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); output.WriteRawVarint32(tag); @@ -333,27 +278,21 @@ public void ReadMaliciouslyLargeBlob() output.Flush(); ms.Position = 0; - CodedInputStream input = CodedInputStream.CreateInstance(ms); - uint testtag; - string ignore; - Assert.IsTrue(input.ReadTag(out testtag, out ignore)); - Assert.AreEqual(tag, testtag); + CodedInputStream input = new CodedInputStream(ms); + Assert.AreEqual(tag, input.ReadTag()); - 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) { 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 +300,12 @@ private static void AssertMessageDepth(TestRecursiveMessage message, int depth) { 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,13 +316,12 @@ public void MaliciousRecursion() 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)); + CodedInputStream input = CodedInputStream.CreateWithLimits(new MemoryStream(data64.ToByteArray()), 1000000, 63); + Assert.Throws(() => TestRecursiveMessage.Parser.ParseFrom(input)); } [Test] @@ -391,27 +329,9 @@ public void SizeLimit() { // Have to use a Stream rather than ByteString.CreateCodedInput as SizeLimit doesn't // apply to the latter case. - MemoryStream ms = new MemoryStream(TestUtil.GetAllSet().ToByteString().ToByteArray()); - CodedInputStream input = CodedInputStream.CreateInstance(ms); - input.SetSizeLimit(16); - - Assert.Throws(() => TestAllTypes.ParseFrom(input)); - } - - [Test] - public void ResetSizeCounter() - { - CodedInputStream input = CodedInputStream.CreateInstance( - new SmallBlockInputStream(new byte[256], 8)); - input.SetSizeLimit(16); - input.ReadRawBytes(16); - - Assert.Throws(() => input.ReadRawByte()); - - input.ResetSizeCounter(); - input.ReadRawByte(); // No exception thrown. - - Assert.Throws(() => input.ReadRawBytes(16)); + MemoryStream ms = new MemoryStream(SampleMessages.CreateFullTestAllTypes().ToByteArray()); + CodedInputStream input = CodedInputStream.CreateWithLimits(ms, 16, 100); + Assert.Throws(() => TestAllTypes.Parser.ParseFrom(input)); } /// @@ -423,7 +343,7 @@ public void ResetSizeCounter() public void ReadInvalidUtf8() { MemoryStream ms = new MemoryStream(); - CodedOutputStream output = CodedOutputStream.CreateInstance(ms); + CodedOutputStream output = new CodedOutputStream(ms); uint tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); output.WriteRawVarint32(tag); @@ -432,15 +352,10 @@ public void ReadInvalidUtf8() output.Flush(); ms.Position = 0; - CodedInputStream input = CodedInputStream.CreateInstance(ms); + CodedInputStream input = new CodedInputStream(ms); - uint testtag; - string ignored; - - Assert.IsTrue(input.ReadTag(out testtag, out ignored)); - Assert.AreEqual(tag, testtag); - string text = null; - input.ReadString(ref text); + Assert.AreEqual(tag, input.ReadTag()); + string text = input.ReadString(); Assert.AreEqual('\ufffd', text[0]); } @@ -465,105 +380,151 @@ public override int Read(byte[] buffer, int offset, int count) } } - 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); - object unk; - TestNegEnum val = TestNegEnum.None; - - Assert.IsTrue(input.ReadEnum(ref val, out unk)); + byte[] bytes = { 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01 }; + CodedInputStream input = new CodedInputStream(bytes); + Assert.AreEqual((int)SampleEnum.NegativeValue, input.ReadEnum()); Assert.IsTrue(input.IsAtEnd); - Assert.AreEqual(TestNegEnum.Value, val); } + //Issue 71: CodedInputStream.ReadBytes go to slow path unnecessarily [Test] - public void TestNegativeEnumPackedArray() + public void TestSlowPathAvoidance() { - int arraySize = 1 + (10 * 5); - 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 }); - - Assert.AreEqual(0, output.SpaceLeft); - - CodedInputStream input = CodedInputStream.CreateInstance(bytes); - uint tag; - string name; - Assert.IsTrue(input.ReadTag(out tag, out name)); + using (var ms = new MemoryStream()) + { + CodedOutputStream output = new CodedOutputStream(ms); + 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(); - List values = new List(); - ICollection unk; - input.ReadEnumArray(tag, name, values, out unk); + ms.Position = 0; + CodedInputStream input = new CodedInputStream(ms, new byte[ms.Length / 2], 0, 0); - Assert.AreEqual(2, values.Count); - Assert.AreEqual(TestNegEnum.None, values[0]); - Assert.AreEqual(TestNegEnum.Value, values[1]); + uint tag = input.ReadTag(); + Assert.AreEqual(1, WireFormat.GetTagFieldNumber(tag)); + Assert.AreEqual(100, input.ReadBytes().Length); - Assert.NotNull(unk); - Assert.AreEqual(4, unk.Count); + tag = input.ReadTag(); + Assert.AreEqual(2, WireFormat.GetTagFieldNumber(tag)); + Assert.AreEqual(100, input.ReadBytes().Length); + } } [Test] - public void TestNegativeEnumArray() + public void Tag0Throws() { - int arraySize = 1 + 1 + (11 * 5); - int msgSize = arraySize; - byte[] bytes = new byte[msgSize]; - CodedOutputStream output = CodedOutputStream.CreateInstance(bytes); - output.WriteInt32Array(8, "", new int[] { 0, -1, -2, -3, -4, -5 }); - - Assert.AreEqual(0, output.SpaceLeft); + var input = new CodedInputStream(new byte[] { 0 }); + Assert.Throws(() => input.ReadTag()); + } - CodedInputStream input = CodedInputStream.CreateInstance(bytes); - uint tag; - string name; - Assert.IsTrue(input.ReadTag(out tag, out name)); + [Test] + public void SkipGroup() + { + // Create an output stream with a group in: + // Field 1: string "field 1" + // Field 2: group containing: + // Field 1: fixed int32 value 100 + // Field 2: string "ignore me" + // Field 3: nested group containing + // Field 1: fixed int64 value 1000 + // Field 3: string "field 3" + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + output.WriteTag(1, WireFormat.WireType.LengthDelimited); + output.WriteString("field 1"); + + // The outer group... + output.WriteTag(2, WireFormat.WireType.StartGroup); + output.WriteTag(1, WireFormat.WireType.Fixed32); + output.WriteFixed32(100); + output.WriteTag(2, WireFormat.WireType.LengthDelimited); + output.WriteString("ignore me"); + // The nested group... + output.WriteTag(3, WireFormat.WireType.StartGroup); + output.WriteTag(1, WireFormat.WireType.Fixed64); + output.WriteFixed64(1000); + // Note: Not sure the field number is relevant for end group... + output.WriteTag(3, WireFormat.WireType.EndGroup); + + // End the outer group + output.WriteTag(2, WireFormat.WireType.EndGroup); + + output.WriteTag(3, WireFormat.WireType.LengthDelimited); + output.WriteString("field 3"); + output.Flush(); + stream.Position = 0; + + // Now act like a generated client + var input = new CodedInputStream(stream); + Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited), input.ReadTag()); + Assert.AreEqual("field 1", input.ReadString()); + Assert.AreEqual(WireFormat.MakeTag(2, WireFormat.WireType.StartGroup), input.ReadTag()); + input.SkipLastField(); // Should consume the whole group, including the nested one. + Assert.AreEqual(WireFormat.MakeTag(3, WireFormat.WireType.LengthDelimited), input.ReadTag()); + Assert.AreEqual("field 3", input.ReadString()); + } - List values = new List(); - ICollection unk; - input.ReadEnumArray(tag, name, values, out unk); + [Test] + public void EndOfStreamReachedWhileSkippingGroup() + { + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + output.WriteTag(1, WireFormat.WireType.StartGroup); + output.WriteTag(2, WireFormat.WireType.StartGroup); + output.WriteTag(2, WireFormat.WireType.EndGroup); - Assert.AreEqual(2, values.Count); - Assert.AreEqual(TestNegEnum.None, values[0]); - Assert.AreEqual(TestNegEnum.Value, values[1]); + output.Flush(); + stream.Position = 0; - Assert.NotNull(unk); - Assert.AreEqual(4, unk.Count); + // Now act like a generated client + var input = new CodedInputStream(stream); + input.ReadTag(); + Assert.Throws(() => input.SkipLastField()); } - //Issue 71: CodedInputStream.ReadBytes go to slow path unnecessarily [Test] - public void TestSlowPathAvoidance() + public void RecursionLimitAppliedWhileSkippingGroup() { - using (var ms = new MemoryStream()) + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + for (int i = 0; i < CodedInputStream.DefaultRecursionLimit + 1; i++) { - 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.Flush(); - - ms.Position = 0; - CodedInputStream input = CodedInputStream.CreateInstance(ms, new byte[ms.Length / 2]); + output.WriteTag(1, WireFormat.WireType.StartGroup); + } + for (int i = 0; i < CodedInputStream.DefaultRecursionLimit + 1; i++) + { + output.WriteTag(1, WireFormat.WireType.EndGroup); + } + output.Flush(); + stream.Position = 0; - uint tag; - string ignore; - ByteString value; + // Now act like a generated client + var input = new CodedInputStream(stream); + Assert.AreEqual(WireFormat.MakeTag(1, WireFormat.WireType.StartGroup), input.ReadTag()); + Assert.Throws(() => input.SkipLastField()); + } - Assert.IsTrue(input.ReadTag(out tag, out ignore)); - Assert.AreEqual(1, WireFormat.GetTagFieldNumber(tag)); - value = ByteString.Empty; - Assert.IsTrue(input.ReadBytes(ref value) && value.Length == 100); + [Test] + public void Construction_Invalid() + { + Assert.Throws(() => new CodedInputStream((byte[]) null)); + Assert.Throws(() => new CodedInputStream(null, 0, 0)); + Assert.Throws(() => new CodedInputStream((Stream) null)); + Assert.Throws(() => new CodedInputStream(new byte[10], 100, 0)); + Assert.Throws(() => new CodedInputStream(new byte[10], 5, 10)); + } - Assert.IsTrue(input.ReadTag(out tag, out ignore)); - Assert.AreEqual(2, WireFormat.GetTagFieldNumber(tag)); - value = ByteString.Empty; - Assert.IsTrue(input.ReadBytes(ref value) && value.Length == 100); - } + [Test] + public void CreateWithLimits_InvalidLimits() + { + var stream = new MemoryStream(); + Assert.Throws(() => CodedInputStream.CreateWithLimits(stream, 0, 1)); + Assert.Throws(() => CodedInputStream.CreateWithLimits(stream, 1, 0)); } } } \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers.Test/CodedOutputStreamTest.cs b/csharp/src/Google.Protobuf.Test/CodedOutputStreamTest.cs similarity index 69% rename from csharp/src/ProtocolBuffers.Test/CodedOutputStreamTest.cs rename to csharp/src/Google.Protobuf.Test/CodedOutputStreamTest.cs index 4d5b83021bfed..3297fe8768117 100644 --- a/csharp/src/ProtocolBuffers.Test/CodedOutputStreamTest.cs +++ b/csharp/src/Google.Protobuf.Test/CodedOutputStreamTest.cs @@ -1,10 +1,7 @@ #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/ +// 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 @@ -31,16 +28,14 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - #endregion using System; -using System.Collections.Generic; using System.IO; -using Google.ProtocolBuffers.TestProtos; +using Google.Protobuf.TestProtos; using NUnit.Framework; -namespace Google.ProtocolBuffers +namespace Google.Protobuf { public class CodedOutputStreamTest { @@ -54,7 +49,7 @@ private static void AssertWriteVarint(byte[] data, ulong value) if ((value >> 32) == 0) { MemoryStream rawOutput = new MemoryStream(); - CodedOutputStream output = CodedOutputStream.CreateInstance(rawOutput); + CodedOutputStream output = new CodedOutputStream(rawOutput); output.WriteRawVarint32((uint) value); output.Flush(); Assert.AreEqual(data, rawOutput.ToArray()); @@ -64,7 +59,7 @@ private static void AssertWriteVarint(byte[] data, ulong value) { MemoryStream rawOutput = new MemoryStream(); - CodedOutputStream output = CodedOutputStream.CreateInstance(rawOutput); + CodedOutputStream output = new CodedOutputStream(rawOutput); output.WriteRawVarint64(value); output.Flush(); Assert.AreEqual(data, rawOutput.ToArray()); @@ -81,7 +76,7 @@ private static void AssertWriteVarint(byte[] data, ulong value) { MemoryStream rawOutput = new MemoryStream(); CodedOutputStream output = - CodedOutputStream.CreateInstance(rawOutput, bufferSize); + new CodedOutputStream(rawOutput, bufferSize); output.WriteRawVarint32((uint) value); output.Flush(); Assert.AreEqual(data, rawOutput.ToArray()); @@ -89,7 +84,7 @@ private static void AssertWriteVarint(byte[] data, ulong value) { MemoryStream rawOutput = new MemoryStream(); - CodedOutputStream output = CodedOutputStream.CreateInstance(rawOutput, bufferSize); + CodedOutputStream output = new CodedOutputStream(rawOutput, bufferSize); output.WriteRawVarint64(value); output.Flush(); Assert.AreEqual(data, rawOutput.ToArray()); @@ -139,7 +134,7 @@ public void WriteVarint() private static void AssertWriteLittleEndian32(byte[] data, uint value) { MemoryStream rawOutput = new MemoryStream(); - CodedOutputStream output = CodedOutputStream.CreateInstance(rawOutput); + CodedOutputStream output = new CodedOutputStream(rawOutput); output.WriteRawLittleEndian32(value); output.Flush(); Assert.AreEqual(data, rawOutput.ToArray()); @@ -148,7 +143,7 @@ private static void AssertWriteLittleEndian32(byte[] data, uint value) for (int bufferSize = 1; bufferSize <= 16; bufferSize *= 2) { rawOutput = new MemoryStream(); - output = CodedOutputStream.CreateInstance(rawOutput, bufferSize); + output = new CodedOutputStream(rawOutput, bufferSize); output.WriteRawLittleEndian32(value); output.Flush(); Assert.AreEqual(data, rawOutput.ToArray()); @@ -162,7 +157,7 @@ private static void AssertWriteLittleEndian32(byte[] data, uint value) private static void AssertWriteLittleEndian64(byte[] data, ulong value) { MemoryStream rawOutput = new MemoryStream(); - CodedOutputStream output = CodedOutputStream.CreateInstance(rawOutput); + CodedOutputStream output = new CodedOutputStream(rawOutput); output.WriteRawLittleEndian64(value); output.Flush(); Assert.AreEqual(data, rawOutput.ToArray()); @@ -171,7 +166,7 @@ private static void AssertWriteLittleEndian64(byte[] data, ulong value) for (int blockSize = 1; blockSize <= 16; blockSize *= 2) { rawOutput = new MemoryStream(); - output = CodedOutputStream.CreateInstance(rawOutput, blockSize); + output = new CodedOutputStream(rawOutput, blockSize); output.WriteRawLittleEndian64(value); output.Flush(); Assert.AreEqual(data, rawOutput.ToArray()); @@ -196,39 +191,23 @@ public void WriteLittleEndian() } [Test] - public void WriteWholeMessage() + public void WriteWholeMessage_VaryingBlockSizes() { - TestAllTypes message = TestUtil.GetAllSet(); + TestAllTypes message = SampleMessages.CreateFullTestAllTypes(); byte[] rawBytes = message.ToByteArray(); - TestUtil.AssertEqualBytes(TestUtil.GoldenMessage.ToByteArray(), rawBytes); // Try different block sizes. for (int blockSize = 1; blockSize < 256; blockSize *= 2) { MemoryStream rawOutput = new MemoryStream(); - CodedOutputStream output = - CodedOutputStream.CreateInstance(rawOutput, blockSize); + CodedOutputStream output = new CodedOutputStream(rawOutput, blockSize); message.WriteTo(output); output.Flush(); - TestUtil.AssertEqualBytes(rawBytes, rawOutput.ToArray()); + Assert.AreEqual(rawBytes, rawOutput.ToArray()); } } - - /// - /// Tests writing a whole message with every packed field type. Ensures the - /// wire format of packed fields is compatible with C++. - /// - [Test] - public void WriteWholePackedFieldsMessage() - { - TestPackedTypes message = TestUtil.GetPackedSet(); - - byte[] rawBytes = message.ToByteArray(); - TestUtil.AssertEqualBytes(TestUtil.GetGoldenPackedFieldsMessage().ToByteArray(), - rawBytes); - } - + [Test] public void EncodeZigZag32() { @@ -293,80 +272,17 @@ public void RoundTripZigZag64() [Test] public void TestNegativeEnumNoTag() { - Assert.AreEqual(10, CodedOutputStream.ComputeInt32SizeNoTag(-2)); - Assert.AreEqual(10, CodedOutputStream.ComputeEnumSizeNoTag(-2)); + Assert.AreEqual(10, CodedOutputStream.ComputeInt32Size(-2)); + Assert.AreEqual(10, CodedOutputStream.ComputeEnumSize((int) SampleEnum.NegativeValue)); byte[] bytes = new byte[10]; - CodedOutputStream output = CodedOutputStream.CreateInstance(bytes); - output.WriteEnumNoTag(-2); + CodedOutputStream output = new CodedOutputStream(bytes); + output.WriteEnum((int) SampleEnum.NegativeValue); Assert.AreEqual(0, output.SpaceLeft); Assert.AreEqual("FE-FF-FF-FF-FF-FF-FF-FF-FF-01", BitConverter.ToString(bytes)); } - [Test] - public void TestNegativeEnumWithTag() - { - Assert.AreEqual(11, CodedOutputStream.ComputeInt32Size(8, -2)); - Assert.AreEqual(11, CodedOutputStream.ComputeEnumSize(8, -2)); - - byte[] bytes = new byte[11]; - CodedOutputStream output = CodedOutputStream.CreateInstance(bytes); - output.WriteEnum(8, "", -2, -2); - - 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() - { - int arraySize = 1 + (10 * 5); - 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 }); - - Assert.AreEqual(0, output.SpaceLeft); - - CodedInputStream input = CodedInputStream.CreateInstance(bytes); - uint tag; - string name; - Assert.IsTrue(input.ReadTag(out tag, out name)); - - List values = new List(); - input.ReadInt32Array(tag, name, values); - - Assert.AreEqual(6, values.Count); - for (int i = 0; i > -6; i--) - Assert.AreEqual(i, values[Math.Abs(i)]); - } - - [Test] - public void TestNegativeEnumArray() - { - int arraySize = 1 + 1 + (11 * 5); - int msgSize = arraySize; - byte[] bytes = new byte[msgSize]; - CodedOutputStream output = CodedOutputStream.CreateInstance(bytes); - output.WriteEnumArray(8, "", new int[] { 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)); - - List values = new List(); - input.ReadInt32Array(tag, name, values); - - Assert.AreEqual(6, values.Count); - for (int i = 0; i > -6; i--) - Assert.AreEqual(i, values[Math.Abs(i)]); - } - [Test] public void TestCodedInputOutputPosition() { @@ -377,92 +293,96 @@ public void TestCodedInputOutputPosition() byte[] child = new byte[120]; { MemoryStream ms = new MemoryStream(child); - CodedOutputStream cout = CodedOutputStream.CreateInstance(ms, 20); + CodedOutputStream cout = new CodedOutputStream(ms, 20); // 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(); } byte[] bytes = new byte[130]; { - CodedOutputStream cout = CodedOutputStream.CreateInstance(bytes); + CodedOutputStream cout = new CodedOutputStream(bytes); // 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(); } - //Now test Input stream: + // Now test Input stream: { - CodedInputStream cin = CodedInputStream.CreateInstance(new MemoryStream(bytes), new byte[50]); - uint tag; - int intValue = 0; - string ignore; + CodedInputStream cin = new CodedInputStream(new MemoryStream(bytes), new byte[50], 0, 0); Assert.AreEqual(0, cin.Position); // Field 1: - Assert.IsTrue(cin.ReadTag(out tag, out ignore) && tag >> 3 == 1); + uint tag = cin.ReadTag(); + Assert.AreEqual(1, tag >> 3); 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); + tag = cin.ReadTag(); + Assert.AreEqual(2, tag >> 3); Assert.AreEqual(4, cin.Position); - uint childlen = cin.ReadRawVarint32(); - Assert.AreEqual(120u, childlen); + int childlen = cin.ReadLength(); + Assert.AreEqual(120, childlen); Assert.AreEqual(5, cin.Position); int oldlimit = cin.PushLimit((int)childlen); Assert.AreEqual(5, cin.Position); // Now we are reading child message { // Field 11: numeric value: 500 - Assert.IsTrue(cin.ReadTag(out tag, out ignore) && tag >> 3 == 11); + tag = cin.ReadTag(); + Assert.AreEqual(11, tag >> 3); 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); + tag = cin.ReadTag(); + Assert.AreEqual(12, tag >> 3); 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); + tag = cin.ReadTag(); + Assert.AreEqual(13, tag >> 3); // 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); + tag = cin.ReadTag(); + Assert.AreEqual(3, tag >> 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/Google.Protobuf.Test/Collections/MapFieldTest.cs b/csharp/src/Google.Protobuf.Test/Collections/MapFieldTest.cs new file mode 100644 index 0000000000000..29c4c2a9c1271 --- /dev/null +++ b/csharp/src/Google.Protobuf.Test/Collections/MapFieldTest.cs @@ -0,0 +1,570 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using System; +using System.Collections.Generic; +using Google.Protobuf.TestProtos; +using NUnit.Framework; +using System.Collections; +using System.Linq; + +namespace Google.Protobuf.Collections +{ + /// + /// Tests for MapField which aren't reliant on the encoded format - + /// tests for serialization/deserialization are part of GeneratedMessageTest. + /// + public class MapFieldTest + { + [Test] + public void Clone_ClonesMessages() + { + var message = new ForeignMessage { C = 20 }; + var map = new MapField { { "x", message } }; + var clone = map.Clone(); + map["x"].C = 30; + Assert.AreEqual(20, clone["x"].C); + } + + [Test] + public void NullValues() + { + TestNullValues(0); + TestNullValues(""); + TestNullValues(new TestAllTypes()); + } + + private void TestNullValues(T nonNullValue) + { + var map = new MapField(false); + var nullValue = (T) (object) null; + Assert.Throws(() => map.Add(0, nullValue)); + Assert.Throws(() => map[0] = nullValue); + map.Add(1, nonNullValue); + map[1] = nonNullValue; + + // Doesn't throw... + map = new MapField(true); + map.Add(0, nullValue); + map[0] = nullValue; + map.Add(1, nonNullValue); + map[1] = nonNullValue; + } + + [Test] + public void Add_ForbidsNullKeys() + { + var map = new MapField(); + Assert.Throws(() => map.Add(null, new ForeignMessage())); + } + + [Test] + public void Indexer_ForbidsNullKeys() + { + var map = new MapField(); + Assert.Throws(() => map[null] = new ForeignMessage()); + } + + [Test] + public void AddPreservesInsertionOrder() + { + var map = new MapField(); + map.Add("a", "v1"); + map.Add("b", "v2"); + map.Add("c", "v3"); + map.Remove("b"); + map.Add("d", "v4"); + CollectionAssert.AreEqual(new[] { "a", "c", "d" }, map.Keys); + CollectionAssert.AreEqual(new[] { "v1", "v3", "v4" }, map.Values); + } + + [Test] + public void EqualityIsOrderInsensitive() + { + var map1 = new MapField(); + map1.Add("a", "v1"); + map1.Add("b", "v2"); + + var map2 = new MapField(); + map2.Add("b", "v2"); + map2.Add("a", "v1"); + + EqualityTester.AssertEquality(map1, map2); + } + + [Test] + public void EqualityIsKeySensitive() + { + var map1 = new MapField(); + map1.Add("first key", "v1"); + map1.Add("second key", "v2"); + + var map2 = new MapField(); + map2.Add("third key", "v1"); + map2.Add("fourth key", "v2"); + + EqualityTester.AssertInequality(map1, map2); + } + + [Test] + public void Equality_Simple() + { + var map = new MapField(); + EqualityTester.AssertEquality(map, map); + EqualityTester.AssertInequality(map, null); + Assert.IsFalse(map.Equals(new object())); + } + + [Test] + public void EqualityIsValueSensitive() + { + // Note: Without some care, it's a little easier than one might + // hope to see hash collisions, but only in some environments... + var map1 = new MapField(); + map1.Add("a", "first value"); + map1.Add("b", "second value"); + + var map2 = new MapField(); + map2.Add("a", "third value"); + map2.Add("b", "fourth value"); + + EqualityTester.AssertInequality(map1, map2); + } + + [Test] + public void EqualityHandlesNullValues() + { + var map1 = new MapField(); + map1.Add("a", new ForeignMessage { C = 10 }); + map1.Add("b", null); + + var map2 = new MapField(); + map2.Add("a", new ForeignMessage { C = 10 }); + map2.Add("b", null); + + EqualityTester.AssertEquality(map1, map2); + // Check the null value isn't ignored entirely... + Assert.IsTrue(map1.Remove("b")); + EqualityTester.AssertInequality(map1, map2); + map1.Add("b", new ForeignMessage()); + EqualityTester.AssertInequality(map1, map2); + map1["b"] = null; + EqualityTester.AssertEquality(map1, map2); + } + + [Test] + public void Add_Dictionary() + { + var map1 = new MapField + { + { "x", "y" }, + { "a", "b" } + }; + var map2 = new MapField + { + { "before", "" }, + map1, + { "after", "" } + }; + var expected = new MapField + { + { "before", "" }, + { "x", "y" }, + { "a", "b" }, + { "after", "" } + }; + Assert.AreEqual(expected, map2); + CollectionAssert.AreEqual(new[] { "before", "x", "a", "after" }, map2.Keys); + } + + // General IDictionary behavior tests + [Test] + public void Add_KeyAlreadyExists() + { + var map = new MapField(); + map.Add("foo", "bar"); + Assert.Throws(() => map.Add("foo", "baz")); + } + + [Test] + public void Add_Pair() + { + var map = new MapField(); + ICollection> collection = map; + collection.Add(NewKeyValuePair("x", "y")); + Assert.AreEqual("y", map["x"]); + Assert.Throws(() => collection.Add(NewKeyValuePair("x", "z"))); + } + + [Test] + public void Contains_Pair() + { + var map = new MapField { { "x", "y" } }; + ICollection> collection = map; + Assert.IsTrue(collection.Contains(NewKeyValuePair("x", "y"))); + Assert.IsFalse(collection.Contains(NewKeyValuePair("x", "z"))); + Assert.IsFalse(collection.Contains(NewKeyValuePair("z", "y"))); + } + + [Test] + public void Remove_Key() + { + var map = new MapField(); + map.Add("foo", "bar"); + Assert.AreEqual(1, map.Count); + Assert.IsFalse(map.Remove("missing")); + Assert.AreEqual(1, map.Count); + Assert.IsTrue(map.Remove("foo")); + Assert.AreEqual(0, map.Count); + Assert.Throws(() => map.Remove(null)); + } + + [Test] + public void Remove_Pair() + { + var map = new MapField(); + map.Add("foo", "bar"); + ICollection> collection = map; + Assert.AreEqual(1, map.Count); + Assert.IsFalse(collection.Remove(NewKeyValuePair("wrong key", "bar"))); + Assert.AreEqual(1, map.Count); + Assert.IsFalse(collection.Remove(NewKeyValuePair("foo", "wrong value"))); + Assert.AreEqual(1, map.Count); + Assert.IsTrue(collection.Remove(NewKeyValuePair("foo", "bar"))); + Assert.AreEqual(0, map.Count); + Assert.Throws(() => collection.Remove(new KeyValuePair(null, ""))); + } + + [Test] + public void CopyTo_Pair() + { + var map = new MapField(); + map.Add("foo", "bar"); + ICollection> collection = map; + KeyValuePair[] array = new KeyValuePair[3]; + collection.CopyTo(array, 1); + Assert.AreEqual(NewKeyValuePair("foo", "bar"), array[1]); + } + + [Test] + public void Clear() + { + var map = new MapField { { "x", "y" } }; + Assert.AreEqual(1, map.Count); + map.Clear(); + Assert.AreEqual(0, map.Count); + map.Add("x", "y"); + Assert.AreEqual(1, map.Count); + } + + [Test] + public void Indexer_Get() + { + var map = new MapField { { "x", "y" } }; + Assert.AreEqual("y", map["x"]); + Assert.Throws(() => { var ignored = map["z"]; }); + } + + [Test] + public void Indexer_Set() + { + var map = new MapField(); + map["x"] = "y"; + Assert.AreEqual("y", map["x"]); + map["x"] = "z"; // This won't throw, unlike Add. + Assert.AreEqual("z", map["x"]); + } + + [Test] + public void GetEnumerator_NonGeneric() + { + IEnumerable map = new MapField { { "x", "y" } }; + CollectionAssert.AreEqual(new[] { new KeyValuePair("x", "y") }, + map.Cast().ToList()); + } + + // Test for the explicitly-implemented non-generic IDictionary interface + [Test] + public void IDictionary_GetEnumerator() + { + IDictionary map = new MapField { { "x", "y" } }; + var enumerator = map.GetEnumerator(); + + // Commented assertions show an ideal situation - it looks like + // the LinkedList enumerator doesn't throw when you ask for the current entry + // at an inappropriate time; fixing this would be more work than it's worth. + // Assert.Throws(() => enumerator.Current.GetHashCode()); + Assert.IsTrue(enumerator.MoveNext()); + Assert.AreEqual("x", enumerator.Key); + Assert.AreEqual("y", enumerator.Value); + Assert.AreEqual(new DictionaryEntry("x", "y"), enumerator.Current); + Assert.AreEqual(new DictionaryEntry("x", "y"), enumerator.Entry); + Assert.IsFalse(enumerator.MoveNext()); + // Assert.Throws(() => enumerator.Current.GetHashCode()); + enumerator.Reset(); + // Assert.Throws(() => enumerator.Current.GetHashCode()); + Assert.IsTrue(enumerator.MoveNext()); + Assert.AreEqual("x", enumerator.Key); // Assume the rest are okay + } + + [Test] + public void IDictionary_Add() + { + var map = new MapField { { "x", "y" } }; + IDictionary dictionary = map; + dictionary.Add("a", "b"); + Assert.AreEqual("b", map["a"]); + Assert.Throws(() => dictionary.Add("a", "duplicate")); + Assert.Throws(() => dictionary.Add(new object(), "key is bad")); + Assert.Throws(() => dictionary.Add("value is bad", new object())); + } + + [Test] + public void IDictionary_Contains() + { + var map = new MapField { { "x", "y" } }; + IDictionary dictionary = map; + + Assert.IsFalse(dictionary.Contains("a")); + Assert.IsFalse(dictionary.Contains(5)); + // Surprising, but IDictionary.Contains is only about keys. + Assert.IsFalse(dictionary.Contains(new DictionaryEntry("x", "y"))); + Assert.IsTrue(dictionary.Contains("x")); + } + + [Test] + public void IDictionary_Remove() + { + var map = new MapField { { "x", "y" } }; + IDictionary dictionary = map; + dictionary.Remove("a"); + Assert.AreEqual(1, dictionary.Count); + dictionary.Remove(5); + Assert.AreEqual(1, dictionary.Count); + dictionary.Remove(new DictionaryEntry("x", "y")); + Assert.AreEqual(1, dictionary.Count); + dictionary.Remove("x"); + Assert.AreEqual(0, dictionary.Count); + Assert.Throws(() => dictionary.Remove(null)); + } + + [Test] + public void IDictionary_CopyTo() + { + var map = new MapField { { "x", "y" } }; + IDictionary dictionary = map; + var array = new DictionaryEntry[3]; + dictionary.CopyTo(array, 1); + CollectionAssert.AreEqual(new[] { default(DictionaryEntry), new DictionaryEntry("x", "y"), default(DictionaryEntry) }, + array); + var objectArray = new object[3]; + dictionary.CopyTo(objectArray, 1); + CollectionAssert.AreEqual(new object[] { null, new DictionaryEntry("x", "y"), null }, + objectArray); + } + + [Test] + public void IDictionary_IsFixedSize() + { + var map = new MapField { { "x", "y" } }; + IDictionary dictionary = map; + Assert.IsFalse(dictionary.IsFixedSize); + } + + [Test] + public void IDictionary_Keys() + { + IDictionary dictionary = new MapField { { "x", "y" } }; + CollectionAssert.AreEqual(new[] { "x" }, dictionary.Keys); + } + + [Test] + public void IDictionary_Values() + { + IDictionary dictionary = new MapField { { "x", "y" } }; + CollectionAssert.AreEqual(new[] { "y" }, dictionary.Values); + } + + [Test] + public void IDictionary_IsSynchronized() + { + IDictionary dictionary = new MapField { { "x", "y" } }; + Assert.IsFalse(dictionary.IsSynchronized); + } + + [Test] + public void IDictionary_SyncRoot() + { + IDictionary dictionary = new MapField { { "x", "y" } }; + Assert.AreSame(dictionary, dictionary.SyncRoot); + } + + [Test] + public void IDictionary_Indexer_Get() + { + IDictionary dictionary = new MapField { { "x", "y" } }; + Assert.AreEqual("y", dictionary["x"]); + Assert.IsNull(dictionary["a"]); + Assert.IsNull(dictionary[5]); + Assert.Throws(() => dictionary[null].GetHashCode()); + } + + [Test] + public void IDictionary_Indexer_Set() + { + var map = new MapField { { "x", "y" } }; + IDictionary dictionary = map; + map["a"] = "b"; + Assert.AreEqual("b", map["a"]); + map["a"] = "c"; + Assert.AreEqual("c", map["a"]); + Assert.Throws(() => dictionary[5] = "x"); + Assert.Throws(() => dictionary["x"] = 5); + Assert.Throws(() => dictionary[null] = "z"); + Assert.Throws(() => dictionary["x"] = null); + } + + [Test] + public void AllowNullValues_Property() + { + // Non-message reference type values are non-nullable by default, but can be overridden + Assert.IsFalse(new MapField().AllowsNullValues); + Assert.IsFalse(new MapField(false).AllowsNullValues); + Assert.IsTrue(new MapField(true).AllowsNullValues); + + // Non-nullable value type values are never nullable + Assert.IsFalse(new MapField().AllowsNullValues); + Assert.IsFalse(new MapField(false).AllowsNullValues); + Assert.Throws(() => new MapField(true)); + + // Message type values are nullable by default, but can be overridden + Assert.IsTrue(new MapField().AllowsNullValues); + Assert.IsFalse(new MapField(false).AllowsNullValues); + Assert.IsTrue(new MapField(true).AllowsNullValues); + + // Nullable value type values are nullable by default, but can be overridden + Assert.IsTrue(new MapField().AllowsNullValues); + Assert.IsFalse(new MapField(false).AllowsNullValues); + Assert.IsTrue(new MapField(true).AllowsNullValues); + } + + [Test] + public void KeysReturnsLiveView() + { + var map = new MapField(); + var keys = map.Keys; + CollectionAssert.AreEqual(new string[0], keys); + map["foo"] = "bar"; + map["x"] = "y"; + CollectionAssert.AreEqual(new[] { "foo", "x" }, keys); + } + + [Test] + public void ValuesReturnsLiveView() + { + var map = new MapField(); + var values = map.Values; + CollectionAssert.AreEqual(new string[0], values); + map["foo"] = "bar"; + map["x"] = "y"; + CollectionAssert.AreEqual(new[] { "bar", "y" }, values); + } + + // Just test keys - we know the implementation is the same for values + [Test] + public void ViewsAreReadOnly() + { + var map = new MapField(); + var keys = map.Keys; + Assert.IsTrue(keys.IsReadOnly); + Assert.Throws(() => keys.Clear()); + Assert.Throws(() => keys.Remove("a")); + Assert.Throws(() => keys.Add("a")); + } + + // Just test keys - we know the implementation is the same for values + [Test] + public void ViewCopyTo() + { + var map = new MapField { { "foo", "bar" }, { "x", "y" } }; + var keys = map.Keys; + var array = new string[4]; + Assert.Throws(() => keys.CopyTo(array, 3)); + Assert.Throws(() => keys.CopyTo(array, -1)); + keys.CopyTo(array, 1); + CollectionAssert.AreEqual(new[] { null, "foo", "x", null }, array); + } + + // Just test keys - we know the implementation is the same for values + [Test] + public void NonGenericViewCopyTo() + { + IDictionary map = new MapField { { "foo", "bar" }, { "x", "y" } }; + ICollection keys = map.Keys; + // Note the use of the Array type here rather than string[] + Array array = new string[4]; + Assert.Throws(() => keys.CopyTo(array, 3)); + Assert.Throws(() => keys.CopyTo(array, -1)); + keys.CopyTo(array, 1); + CollectionAssert.AreEqual(new[] { null, "foo", "x", null }, array); + } + + [Test] + public void KeysContains() + { + var map = new MapField { { "foo", "bar" }, { "x", "y" } }; + var keys = map.Keys; + Assert.IsTrue(keys.Contains("foo")); + Assert.IsFalse(keys.Contains("bar")); // It's a value! + Assert.IsFalse(keys.Contains("1")); + // Keys can't be null, so we should prevent contains check + Assert.Throws(() => keys.Contains(null)); + } + + [Test] + public void ValuesContains() + { + var map = new MapField { { "foo", "bar" }, { "x", "y" } }; + var values = map.Values; + Assert.IsTrue(values.Contains("bar")); + Assert.IsFalse(values.Contains("foo")); // It's a key! + Assert.IsFalse(values.Contains("1")); + // Values can be null, so this makes sense + Assert.IsFalse(values.Contains(null)); + } + + private static KeyValuePair NewKeyValuePair(TKey key, TValue value) + { + return new KeyValuePair(key, value); + } + } +} diff --git a/csharp/src/Google.Protobuf.Test/Collections/RepeatedFieldTest.cs b/csharp/src/Google.Protobuf.Test/Collections/RepeatedFieldTest.cs new file mode 100644 index 0000000000000..8c804fdd22863 --- /dev/null +++ b/csharp/src/Google.Protobuf.Test/Collections/RepeatedFieldTest.cs @@ -0,0 +1,603 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using Google.Protobuf.TestProtos; +using NUnit.Framework; + +namespace Google.Protobuf.Collections +{ + public class RepeatedFieldTest + { + [Test] + public void NullValuesRejected() + { + var list = new RepeatedField(); + Assert.Throws(() => list.Add((string)null)); + Assert.Throws(() => list.Add((IEnumerable)null)); + Assert.Throws(() => list.Add((RepeatedField)null)); + Assert.Throws(() => list.Contains(null)); + Assert.Throws(() => list.IndexOf(null)); + } + + [Test] + public void Add_SingleItem() + { + var list = new RepeatedField(); + list.Add("foo"); + Assert.AreEqual(1, list.Count); + Assert.AreEqual("foo", list[0]); + } + + [Test] + public void Add_Sequence() + { + var list = new RepeatedField(); + list.Add(new[] { "foo", "bar" }); + Assert.AreEqual(2, list.Count); + Assert.AreEqual("foo", list[0]); + Assert.AreEqual("bar", list[1]); + } + + [Test] + public void Add_RepeatedField() + { + var list = new RepeatedField { "original" }; + list.Add(new RepeatedField { "foo", "bar" }); + Assert.AreEqual(3, list.Count); + Assert.AreEqual("original", list[0]); + Assert.AreEqual("foo", list[1]); + Assert.AreEqual("bar", list[2]); + } + + [Test] + public void RemoveAt_Valid() + { + var list = new RepeatedField { "first", "second", "third" }; + list.RemoveAt(1); + CollectionAssert.AreEqual(new[] { "first", "third" }, list); + // Just check that these don't throw... + list.RemoveAt(list.Count - 1); // Now the count will be 1... + list.RemoveAt(0); + Assert.AreEqual(0, list.Count); + } + + [Test] + public void RemoveAt_Invalid() + { + var list = new RepeatedField { "first", "second", "third" }; + Assert.Throws(() => list.RemoveAt(-1)); + Assert.Throws(() => list.RemoveAt(3)); + } + + [Test] + public void Insert_Valid() + { + var list = new RepeatedField { "first", "second" }; + list.Insert(1, "middle"); + CollectionAssert.AreEqual(new[] { "first", "middle", "second" }, list); + list.Insert(3, "end"); + CollectionAssert.AreEqual(new[] { "first", "middle", "second", "end" }, list); + list.Insert(0, "start"); + CollectionAssert.AreEqual(new[] { "start", "first", "middle", "second", "end" }, list); + } + + [Test] + public void Insert_Invalid() + { + var list = new RepeatedField { "first", "second" }; + Assert.Throws(() => list.Insert(-1, "foo")); + Assert.Throws(() => list.Insert(3, "foo")); + Assert.Throws(() => list.Insert(0, null)); + } + + [Test] + public void Equals_RepeatedField() + { + var list = new RepeatedField { "first", "second" }; + Assert.IsFalse(list.Equals((RepeatedField) null)); + Assert.IsTrue(list.Equals(list)); + Assert.IsFalse(list.Equals(new RepeatedField { "first", "third" })); + Assert.IsFalse(list.Equals(new RepeatedField { "first" })); + Assert.IsTrue(list.Equals(new RepeatedField { "first", "second" })); + } + + [Test] + public void Equals_Object() + { + var list = new RepeatedField { "first", "second" }; + Assert.IsFalse(list.Equals((object) null)); + Assert.IsTrue(list.Equals((object) list)); + Assert.IsFalse(list.Equals((object) new RepeatedField { "first", "third" })); + Assert.IsFalse(list.Equals((object) new RepeatedField { "first" })); + Assert.IsTrue(list.Equals((object) new RepeatedField { "first", "second" })); + Assert.IsFalse(list.Equals(new object())); + } + + [Test] + public void GetEnumerator_GenericInterface() + { + IEnumerable list = new RepeatedField { "first", "second" }; + // Select gets rid of the optimizations in ToList... + CollectionAssert.AreEqual(new[] { "first", "second" }, list.Select(x => x).ToList()); + } + + [Test] + public void GetEnumerator_NonGenericInterface() + { + IEnumerable list = new RepeatedField { "first", "second" }; + CollectionAssert.AreEqual(new[] { "first", "second" }, list.Cast().ToList()); + } + + [Test] + public void CopyTo() + { + var list = new RepeatedField { "first", "second" }; + string[] stringArray = new string[4]; + list.CopyTo(stringArray, 1); + CollectionAssert.AreEqual(new[] { null, "first", "second", null }, stringArray); + } + + [Test] + public void Indexer_Get() + { + var list = new RepeatedField { "first", "second" }; + Assert.AreEqual("first", list[0]); + Assert.AreEqual("second", list[1]); + Assert.Throws(() => list[-1].GetHashCode()); + Assert.Throws(() => list[2].GetHashCode()); + } + + [Test] + public void Indexer_Set() + { + var list = new RepeatedField { "first", "second" }; + list[0] = "changed"; + Assert.AreEqual("changed", list[0]); + Assert.Throws(() => list[0] = null); + Assert.Throws(() => list[-1] = "bad"); + Assert.Throws(() => list[2] = "bad"); + } + + [Test] + public void Clone_ReturnsMutable() + { + var list = new RepeatedField { 0 }; + var clone = list.Clone(); + clone[0] = 1; + } + + [Test] + public void Enumerator() + { + var list = new RepeatedField { "first", "second" }; + using (var enumerator = list.GetEnumerator()) + { + Assert.IsTrue(enumerator.MoveNext()); + Assert.AreEqual("first", enumerator.Current); + Assert.IsTrue(enumerator.MoveNext()); + Assert.AreEqual("second", enumerator.Current); + Assert.IsFalse(enumerator.MoveNext()); + Assert.IsFalse(enumerator.MoveNext()); + } + } + + [Test] + public void AddEntriesFrom_PackedInt32() + { + uint packedTag = WireFormat.MakeTag(10, WireFormat.WireType.LengthDelimited); + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + var length = CodedOutputStream.ComputeInt32Size(10) + + CodedOutputStream.ComputeInt32Size(999) + + CodedOutputStream.ComputeInt32Size(-1000); + output.WriteTag(packedTag); + output.WriteRawVarint32((uint) length); + output.WriteInt32(10); + output.WriteInt32(999); + output.WriteInt32(-1000); + output.Flush(); + stream.Position = 0; + + // Deliberately "expecting" a non-packed tag, but we detect that the data is + // actually packed. + uint nonPackedTag = WireFormat.MakeTag(10, WireFormat.WireType.LengthDelimited); + var field = new RepeatedField(); + var input = new CodedInputStream(stream); + input.AssertNextTag(packedTag); + field.AddEntriesFrom(input, FieldCodec.ForInt32(nonPackedTag)); + CollectionAssert.AreEqual(new[] { 10, 999, -1000 }, field); + Assert.IsTrue(input.IsAtEnd); + } + + [Test] + public void AddEntriesFrom_NonPackedInt32() + { + uint nonPackedTag = WireFormat.MakeTag(10, WireFormat.WireType.Varint); + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + output.WriteTag(nonPackedTag); + output.WriteInt32(10); + output.WriteTag(nonPackedTag); + output.WriteInt32(999); + output.WriteTag(nonPackedTag); + output.WriteInt32(-1000); // Just for variety... + output.Flush(); + stream.Position = 0; + + // Deliberately "expecting" a packed tag, but we detect that the data is + // actually not packed. + uint packedTag = WireFormat.MakeTag(10, WireFormat.WireType.LengthDelimited); + var field = new RepeatedField(); + var input = new CodedInputStream(stream); + input.AssertNextTag(nonPackedTag); + field.AddEntriesFrom(input, FieldCodec.ForInt32(packedTag)); + CollectionAssert.AreEqual(new[] { 10, 999, -1000 }, field); + Assert.IsTrue(input.IsAtEnd); + } + + [Test] + public void AddEntriesFrom_String() + { + uint tag = WireFormat.MakeTag(10, WireFormat.WireType.LengthDelimited); + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + output.WriteTag(tag); + output.WriteString("Foo"); + output.WriteTag(tag); + output.WriteString(""); + output.WriteTag(tag); + output.WriteString("Bar"); + output.Flush(); + stream.Position = 0; + + var field = new RepeatedField(); + var input = new CodedInputStream(stream); + input.AssertNextTag(tag); + field.AddEntriesFrom(input, FieldCodec.ForString(tag)); + CollectionAssert.AreEqual(new[] { "Foo", "", "Bar" }, field); + Assert.IsTrue(input.IsAtEnd); + } + + [Test] + public void AddEntriesFrom_Message() + { + var message1 = new ForeignMessage { C = 2000 }; + var message2 = new ForeignMessage { C = -250 }; + + uint tag = WireFormat.MakeTag(10, WireFormat.WireType.LengthDelimited); + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + output.WriteTag(tag); + output.WriteMessage(message1); + output.WriteTag(tag); + output.WriteMessage(message2); + output.Flush(); + stream.Position = 0; + + var field = new RepeatedField(); + var input = new CodedInputStream(stream); + input.AssertNextTag(tag); + field.AddEntriesFrom(input, FieldCodec.ForMessage(tag, ForeignMessage.Parser)); + CollectionAssert.AreEqual(new[] { message1, message2}, field); + Assert.IsTrue(input.IsAtEnd); + } + + [Test] + public void WriteTo_PackedInt32() + { + uint tag = WireFormat.MakeTag(10, WireFormat.WireType.LengthDelimited); + var field = new RepeatedField { 10, 1000, 1000000 }; + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + field.WriteTo(output, FieldCodec.ForInt32(tag)); + output.Flush(); + stream.Position = 0; + + var input = new CodedInputStream(stream); + input.AssertNextTag(tag); + var length = input.ReadLength(); + Assert.AreEqual(10, input.ReadInt32()); + Assert.AreEqual(1000, input.ReadInt32()); + Assert.AreEqual(1000000, input.ReadInt32()); + Assert.IsTrue(input.IsAtEnd); + Assert.AreEqual(1 + CodedOutputStream.ComputeLengthSize(length) + length, stream.Length); + } + + [Test] + public void WriteTo_NonPackedInt32() + { + uint tag = WireFormat.MakeTag(10, WireFormat.WireType.Varint); + var field = new RepeatedField { 10, 1000, 1000000}; + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + field.WriteTo(output, FieldCodec.ForInt32(tag)); + output.Flush(); + stream.Position = 0; + + var input = new CodedInputStream(stream); + input.AssertNextTag(tag); + Assert.AreEqual(10, input.ReadInt32()); + input.AssertNextTag(tag); + Assert.AreEqual(1000, input.ReadInt32()); + input.AssertNextTag(tag); + Assert.AreEqual(1000000, input.ReadInt32()); + Assert.IsTrue(input.IsAtEnd); + } + + [Test] + public void WriteTo_String() + { + uint tag = WireFormat.MakeTag(10, WireFormat.WireType.LengthDelimited); + var field = new RepeatedField { "Foo", "", "Bar" }; + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + field.WriteTo(output, FieldCodec.ForString(tag)); + output.Flush(); + stream.Position = 0; + + var input = new CodedInputStream(stream); + input.AssertNextTag(tag); + Assert.AreEqual("Foo", input.ReadString()); + input.AssertNextTag(tag); + Assert.AreEqual("", input.ReadString()); + input.AssertNextTag(tag); + Assert.AreEqual("Bar", input.ReadString()); + Assert.IsTrue(input.IsAtEnd); + } + + [Test] + public void WriteTo_Message() + { + var message1 = new ForeignMessage { C = 20 }; + var message2 = new ForeignMessage { C = 25 }; + uint tag = WireFormat.MakeTag(10, WireFormat.WireType.LengthDelimited); + var field = new RepeatedField { message1, message2 }; + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + field.WriteTo(output, FieldCodec.ForMessage(tag, ForeignMessage.Parser)); + output.Flush(); + stream.Position = 0; + + var input = new CodedInputStream(stream); + input.AssertNextTag(tag); + Assert.AreEqual(message1, input.ReadMessage(ForeignMessage.Parser)); + input.AssertNextTag(tag); + Assert.AreEqual(message2, input.ReadMessage(ForeignMessage.Parser)); + Assert.IsTrue(input.IsAtEnd); + } + + [Test] + public void CalculateSize_VariableSizeNonPacked() + { + var list = new RepeatedField { 1, 500, 1 }; + var tag = WireFormat.MakeTag(1, WireFormat.WireType.Varint); + // 2 bytes for the first entry, 3 bytes for the second, 2 bytes for the third + Assert.AreEqual(7, list.CalculateSize(FieldCodec.ForInt32(tag))); + } + + [Test] + public void CalculateSize_FixedSizeNonPacked() + { + var list = new RepeatedField { 1, 500, 1 }; + var tag = WireFormat.MakeTag(1, WireFormat.WireType.Fixed32); + // 5 bytes for the each entry + Assert.AreEqual(15, list.CalculateSize(FieldCodec.ForSFixed32(tag))); + } + + [Test] + public void CalculateSize_VariableSizePacked() + { + var list = new RepeatedField { 1, 500, 1}; + var tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); + // 1 byte for the tag, 1 byte for the length, + // 1 byte for the first entry, 2 bytes for the second, 1 byte for the third + Assert.AreEqual(6, list.CalculateSize(FieldCodec.ForInt32(tag))); + } + + [Test] + public void CalculateSize_FixedSizePacked() + { + var list = new RepeatedField { 1, 500, 1 }; + var tag = WireFormat.MakeTag(1, WireFormat.WireType.LengthDelimited); + // 1 byte for the tag, 1 byte for the length, 4 bytes per entry + Assert.AreEqual(14, list.CalculateSize(FieldCodec.ForSFixed32(tag))); + } + + [Test] + public void TestNegativeEnumArray() + { + int arraySize = 1 + 1 + (11 * 5); + int msgSize = arraySize; + byte[] bytes = new byte[msgSize]; + CodedOutputStream output = new CodedOutputStream(bytes); + uint tag = WireFormat.MakeTag(8, WireFormat.WireType.Varint); + for (int i = 0; i >= -5; i--) + { + output.WriteTag(tag); + output.WriteEnum(i); + } + + Assert.AreEqual(0, output.SpaceLeft); + + CodedInputStream input = new CodedInputStream(bytes); + tag = input.ReadTag(); + + RepeatedField values = new RepeatedField(); + values.AddEntriesFrom(input, FieldCodec.ForEnum(tag, x => (int)x, x => (SampleEnum)x)); + + Assert.AreEqual(6, values.Count); + Assert.AreEqual(SampleEnum.None, values[0]); + Assert.AreEqual(((SampleEnum)(-1)), values[1]); + Assert.AreEqual(SampleEnum.NegativeValue, values[2]); + Assert.AreEqual(((SampleEnum)(-3)), values[3]); + Assert.AreEqual(((SampleEnum)(-4)), values[4]); + Assert.AreEqual(((SampleEnum)(-5)), values[5]); + } + + + [Test] + public void TestNegativeEnumPackedArray() + { + int arraySize = 1 + (10 * 5); + int msgSize = 1 + 1 + arraySize; + byte[] bytes = new byte[msgSize]; + CodedOutputStream output = new CodedOutputStream(bytes); + // Length-delimited to show we want the packed representation + uint tag = WireFormat.MakeTag(8, WireFormat.WireType.LengthDelimited); + output.WriteTag(tag); + int size = 0; + for (int i = 0; i >= -5; i--) + { + size += CodedOutputStream.ComputeEnumSize(i); + } + output.WriteRawVarint32((uint)size); + for (int i = 0; i >= -5; i--) + { + output.WriteEnum(i); + } + Assert.AreEqual(0, output.SpaceLeft); + + CodedInputStream input = new CodedInputStream(bytes); + tag = input.ReadTag(); + + RepeatedField values = new RepeatedField(); + values.AddEntriesFrom(input, FieldCodec.ForEnum(tag, x => (int)x, x => (SampleEnum)x)); + + Assert.AreEqual(6, values.Count); + Assert.AreEqual(SampleEnum.None, values[0]); + Assert.AreEqual(((SampleEnum)(-1)), values[1]); + Assert.AreEqual(SampleEnum.NegativeValue, values[2]); + Assert.AreEqual(((SampleEnum)(-3)), values[3]); + Assert.AreEqual(((SampleEnum)(-4)), values[4]); + Assert.AreEqual(((SampleEnum)(-5)), values[5]); + } + + // Fairly perfunctory tests for the non-generic IList implementation + [Test] + public void IList_Indexer() + { + var field = new RepeatedField { "first", "second" }; + IList list = field; + Assert.AreEqual("first", list[0]); + list[1] = "changed"; + Assert.AreEqual("changed", field[1]); + } + + [Test] + public void IList_Contains() + { + IList list = new RepeatedField { "first", "second" }; + Assert.IsTrue(list.Contains("second")); + Assert.IsFalse(list.Contains("third")); + Assert.IsFalse(list.Contains(new object())); + } + + [Test] + public void IList_Add() + { + IList list = new RepeatedField { "first", "second" }; + list.Add("third"); + CollectionAssert.AreEqual(new[] { "first", "second", "third" }, list); + } + + [Test] + public void IList_Remove() + { + IList list = new RepeatedField { "first", "second" }; + list.Remove("third"); // No-op, no exception + list.Remove(new object()); // No-op, no exception + list.Remove("first"); + CollectionAssert.AreEqual(new[] { "second" }, list); + } + + [Test] + public void IList_IsFixedSize() + { + var field = new RepeatedField { "first", "second" }; + IList list = field; + Assert.IsFalse(list.IsFixedSize); + } + + [Test] + public void IList_IndexOf() + { + IList list = new RepeatedField { "first", "second" }; + Assert.AreEqual(1, list.IndexOf("second")); + Assert.AreEqual(-1, list.IndexOf("third")); + Assert.AreEqual(-1, list.IndexOf(new object())); + } + + [Test] + public void IList_SyncRoot() + { + IList list = new RepeatedField { "first", "second" }; + Assert.AreSame(list, list.SyncRoot); + } + + [Test] + public void IList_CopyTo() + { + IList list = new RepeatedField { "first", "second" }; + string[] stringArray = new string[4]; + list.CopyTo(stringArray, 1); + CollectionAssert.AreEqual(new[] { null, "first", "second", null }, stringArray); + + object[] objectArray = new object[4]; + list.CopyTo(objectArray, 1); + CollectionAssert.AreEqual(new[] { null, "first", "second", null }, objectArray); + + Assert.Throws(() => list.CopyTo(new StringBuilder[4], 1)); + Assert.Throws(() => list.CopyTo(new int[4], 1)); + } + + [Test] + public void IList_IsSynchronized() + { + IList list = new RepeatedField { "first", "second" }; + Assert.IsFalse(list.IsSynchronized); + } + + [Test] + public void IList_Insert() + { + IList list = new RepeatedField { "first", "second" }; + list.Insert(1, "middle"); + CollectionAssert.AreEqual(new[] { "first", "middle", "second" }, list); + } + } +} diff --git a/csharp/src/Google.Protobuf.Test/Compatibility/PropertyInfoExtensionsTest.cs b/csharp/src/Google.Protobuf.Test/Compatibility/PropertyInfoExtensionsTest.cs new file mode 100644 index 0000000000000..df23a09cd4c4d --- /dev/null +++ b/csharp/src/Google.Protobuf.Test/Compatibility/PropertyInfoExtensionsTest.cs @@ -0,0 +1,98 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using NUnit.Framework; +using System.Reflection; + +namespace Google.Protobuf.Compatibility +{ + public class PropertyInfoExtensionsTest + { + public string PublicReadWrite { get; set; } + private string PrivateReadWrite { get; set; } + public string PublicReadPrivateWrite { get; private set; } + public string PrivateReadPublicWrite { private get; set; } + public string PublicReadOnly { get { return null; } } + private string PrivateReadOnly { get { return null; } } + public string PublicWriteOnly { set { } } + private string PrivateWriteOnly { set { } } + + [Test] + [TestCase("PublicReadWrite")] + [TestCase("PublicReadPrivateWrite")] + [TestCase("PublicReadOnly")] + public void GetGetMethod_Success(string name) + { + var propertyInfo = typeof(PropertyInfoExtensionsTest) + .GetProperty(name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); + Assert.IsNotNull(PropertyInfoExtensions.GetGetMethod(propertyInfo)); + } + + [Test] + [TestCase("PrivateReadWrite")] + [TestCase("PrivateReadPublicWrite")] + [TestCase("PrivateReadOnly")] + [TestCase("PublicWriteOnly")] + [TestCase("PrivateWriteOnly")] + public void GetGetMethod_NoAccessibleGetter(string name) + { + var propertyInfo = typeof(PropertyInfoExtensionsTest) + .GetProperty(name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); + Assert.IsNull(PropertyInfoExtensions.GetGetMethod(propertyInfo)); + } + + [Test] + [TestCase("PublicReadWrite")] + [TestCase("PrivateReadPublicWrite")] + [TestCase("PublicWriteOnly")] + public void GetSetMethod_Success(string name) + { + var propertyInfo = typeof(PropertyInfoExtensionsTest) + .GetProperty(name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); + Assert.IsNotNull(PropertyInfoExtensions.GetSetMethod(propertyInfo)); + } + + [Test] + [TestCase("PublicReadPrivateWrite")] + [TestCase("PrivateReadWrite")] + [TestCase("PrivateReadOnly")] + [TestCase("PublicReadOnly")] + [TestCase("PrivateWriteOnly")] + public void GetSetMethod_NoAccessibleGetter(string name) + { + var propertyInfo = typeof(PropertyInfoExtensionsTest) + .GetProperty(name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); + Assert.IsNull(PropertyInfoExtensions.GetSetMethod(propertyInfo)); + } + } + +} diff --git a/csharp/src/Google.Protobuf.Test/Compatibility/TypeExtensionsTest.cs b/csharp/src/Google.Protobuf.Test/Compatibility/TypeExtensionsTest.cs new file mode 100644 index 0000000000000..f0c8d3bcc6e3d --- /dev/null +++ b/csharp/src/Google.Protobuf.Test/Compatibility/TypeExtensionsTest.cs @@ -0,0 +1,133 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion +using NUnit.Framework; +using System; +using System.Collections.Generic; +using System.Reflection; + +namespace Google.Protobuf.Compatibility +{ + public class TypeExtensionsTest + { + public class DerivedList : List { } + public string PublicProperty { get; set; } + private string PrivateProperty { get; set; } + + public void PublicMethod() + { + } + + private void PrivateMethod() + { + } + + [Test] + [TestCase(typeof(int), true)] + [TestCase(typeof(int?), true)] + [TestCase(typeof(Nullable<>), true)] + [TestCase(typeof(WireFormat.WireType), true)] + [TestCase(typeof(string), false)] + [TestCase(typeof(object), false)] + [TestCase(typeof(Enum), false)] + [TestCase(typeof(ValueType), false)] + [TestCase(typeof(TypeExtensionsTest), false)] + [TestCase(typeof(Action), false)] + [TestCase(typeof(Action<>), false)] + [TestCase(typeof(IDisposable), false)] + public void IsValueType(Type type, bool expected) + { + Assert.AreEqual(expected, TypeExtensions.IsValueType(type)); + } + + [Test] + [TestCase(typeof(object), typeof(string), true)] + [TestCase(typeof(object), typeof(int), true)] + [TestCase(typeof(string), typeof(string), true)] + [TestCase(typeof(string), typeof(object), false)] + [TestCase(typeof(string), typeof(int), false)] + [TestCase(typeof(int), typeof(int), true)] + [TestCase(typeof(ValueType), typeof(int), true)] + [TestCase(typeof(long), typeof(int), false)] // + public void IsAssignableFrom(Type target, Type argument, bool expected) + { + Assert.AreEqual(expected, TypeExtensions.IsAssignableFrom(target, argument)); + } + + [Test] + [TestCase(typeof(DerivedList), "Count")] // Go up the type hierarchy + [TestCase(typeof(List), "Count")] + [TestCase(typeof(List<>), "Count")] + [TestCase(typeof(TypeExtensionsTest), "PublicProperty")] + public void GetProperty_Success(Type type, string name) + { + var property = TypeExtensions.GetProperty(type, name); + Assert.IsNotNull(property); + Assert.AreEqual(name, property.Name); + } + + [Test] + [TestCase(typeof(TypeExtensionsTest), "PrivateProperty")] + [TestCase(typeof(TypeExtensionsTest), "Garbage")] + public void GetProperty_NoSuchProperty(Type type, string name) + { + var property = TypeExtensions.GetProperty(type, name); + Assert.IsNull(property); + } + + [Test] + [TestCase(typeof(DerivedList), "RemoveAt")] // Go up the type hierarchy + [TestCase(typeof(List<>), "RemoveAt")] + [TestCase(typeof(TypeExtensionsTest), "PublicMethod")] + public void GetMethod_Success(Type type, string name) + { + var method = TypeExtensions.GetMethod(type, name); + Assert.IsNotNull(method); + Assert.AreEqual(name, method.Name); + } + + [Test] + [TestCase(typeof(TypeExtensionsTest), "PrivateMethod")] + [TestCase(typeof(TypeExtensionsTest), "GarbageMethod")] + public void GetMethod_NoSuchMethod(Type type, string name) + { + var method = TypeExtensions.GetMethod(type, name); + Assert.IsNull(method); + } + + [Test] + [TestCase(typeof(List), "IndexOf")] + public void GetMethod_Ambiguous(Type type, string name) + { + Assert.Throws(() => TypeExtensions.GetMethod(type, name)); + } + } +} diff --git a/csharp/src/Google.Protobuf.Test/DeprecatedMemberTest.cs b/csharp/src/Google.Protobuf.Test/DeprecatedMemberTest.cs new file mode 100644 index 0000000000000..34d5b9f98cbb4 --- /dev/null +++ b/csharp/src/Google.Protobuf.Test/DeprecatedMemberTest.cs @@ -0,0 +1,55 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using System; +using System.Reflection; +using Google.Protobuf.TestProtos; +using NUnit.Framework; + +namespace Google.Protobuf +{ + public class DeprecatedMemberTest + { + private static void AssertIsDeprecated(MemberInfo member) + { + Assert.NotNull(member); + Assert.IsTrue(member.IsDefined(typeof(ObsoleteAttribute), false), "Member not obsolete: " + member); + } + + [Test] + public void TestDepreatedPrimitiveValue() + { + AssertIsDeprecated(typeof(TestDeprecatedFields).GetProperty("DeprecatedInt32")); + } + + } +} diff --git a/csharp/src/Google.Protobuf.Test/EqualityTester.cs b/csharp/src/Google.Protobuf.Test/EqualityTester.cs new file mode 100644 index 0000000000000..a669baba17bfd --- /dev/null +++ b/csharp/src/Google.Protobuf.Test/EqualityTester.cs @@ -0,0 +1,64 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using System; +using NUnit.Framework; + +namespace Google.Protobuf +{ + /// + /// Helper methods when testing equality. NUnit's Assert.AreEqual and + /// Assert.AreNotEqual methods try to be clever with collections, which can + /// be annoying... + /// + internal static class EqualityTester + { + public static void AssertEquality(T first, T second) where T : IEquatable + { + Assert.IsTrue(first.Equals(second)); + Assert.IsTrue(first.Equals((object) second)); + Assert.AreEqual(first.GetHashCode(), second.GetHashCode()); + } + + public static void AssertInequality(T first, T second) where T : IEquatable + { + Assert.IsFalse(first.Equals(second)); + Assert.IsFalse(first.Equals((object) second)); + // While this isn't a requirement, the chances of this test failing due to + // coincidence rather than a bug are very small. + if (first != null && second != null) + { + Assert.AreNotEqual(first.GetHashCode(), second.GetHashCode()); + } + } + } +} diff --git a/csharp/src/Google.Protobuf.Test/FieldCodecTest.cs b/csharp/src/Google.Protobuf.Test/FieldCodecTest.cs new file mode 100644 index 0000000000000..38ba227f6d50e --- /dev/null +++ b/csharp/src/Google.Protobuf.Test/FieldCodecTest.cs @@ -0,0 +1,195 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using System.Collections.Generic; +using System.IO; +using Google.Protobuf.TestProtos; +using NUnit.Framework; + +namespace Google.Protobuf +{ + public class FieldCodecTest + { +#pragma warning disable 0414 // Used by tests via reflection - do not remove! + private static readonly List Codecs = new List + { + new FieldCodecTestData(FieldCodec.ForBool(100), true, "Bool"), + new FieldCodecTestData(FieldCodec.ForString(100), "sample", "String"), + new FieldCodecTestData(FieldCodec.ForBytes(100), ByteString.CopyFrom(1, 2, 3), "Bytes"), + new FieldCodecTestData(FieldCodec.ForInt32(100), -1000, "Int32"), + new FieldCodecTestData(FieldCodec.ForSInt32(100), -1000, "SInt32"), + new FieldCodecTestData(FieldCodec.ForSFixed32(100), -1000, "SFixed32"), + new FieldCodecTestData(FieldCodec.ForUInt32(100), 1234, "UInt32"), + new FieldCodecTestData(FieldCodec.ForFixed32(100), 1234, "Fixed32"), + new FieldCodecTestData(FieldCodec.ForInt64(100), -1000, "Int64"), + new FieldCodecTestData(FieldCodec.ForSInt64(100), -1000, "SInt64"), + new FieldCodecTestData(FieldCodec.ForSFixed64(100), -1000, "SFixed64"), + new FieldCodecTestData(FieldCodec.ForUInt64(100), 1234, "UInt64"), + new FieldCodecTestData(FieldCodec.ForFixed64(100), 1234, "Fixed64"), + new FieldCodecTestData(FieldCodec.ForFloat(100), 1234.5f, "Float"), + new FieldCodecTestData(FieldCodec.ForDouble(100), 1234567890.5d, "Double"), + new FieldCodecTestData( + FieldCodec.ForEnum(100, t => (int) t, t => (ForeignEnum) t), ForeignEnum.FOREIGN_BAZ, "Enum"), + new FieldCodecTestData( + FieldCodec.ForMessage(100, ForeignMessage.Parser), new ForeignMessage { C = 10 }, "Message"), + }; +#pragma warning restore 0414 + + [Test, TestCaseSource("Codecs")] + public void RoundTripWithTag(ICodecTestData codec) + { + codec.TestRoundTripWithTag(); + } + + [Test, TestCaseSource("Codecs")] + public void RoundTripRaw(ICodecTestData codec) + { + codec.TestRoundTripRaw(); + } + + [Test, TestCaseSource("Codecs")] + public void CalculateSize(ICodecTestData codec) + { + codec.TestCalculateSizeWithTag(); + } + + [Test, TestCaseSource("Codecs")] + public void DefaultValue(ICodecTestData codec) + { + codec.TestDefaultValue(); + } + + [Test, TestCaseSource("Codecs")] + public void FixedSize(ICodecTestData codec) + { + codec.TestFixedSize(); + } + + // This is ugly, but it means we can have a non-generic interface. + // It feels like NUnit should support this better, but I don't know + // of any better ways right now. + public interface ICodecTestData + { + void TestRoundTripRaw(); + void TestRoundTripWithTag(); + void TestCalculateSizeWithTag(); + void TestDefaultValue(); + void TestFixedSize(); + } + + public class FieldCodecTestData : ICodecTestData + { + private readonly FieldCodec codec; + private readonly T sampleValue; + private readonly string name; + + public FieldCodecTestData(FieldCodec codec, T sampleValue, string name) + { + this.codec = codec; + this.sampleValue = sampleValue; + this.name = name; + } + + public void TestRoundTripRaw() + { + var stream = new MemoryStream(); + var codedOutput = new CodedOutputStream(stream); + codec.ValueWriter(codedOutput, sampleValue); + codedOutput.Flush(); + stream.Position = 0; + var codedInput = new CodedInputStream(stream); + Assert.AreEqual(sampleValue, codec.ValueReader(codedInput)); + Assert.IsTrue(codedInput.IsAtEnd); + } + + public void TestRoundTripWithTag() + { + var stream = new MemoryStream(); + var codedOutput = new CodedOutputStream(stream); + codec.WriteTagAndValue(codedOutput, sampleValue); + codedOutput.Flush(); + stream.Position = 0; + var codedInput = new CodedInputStream(stream); + codedInput.AssertNextTag(codec.Tag); + Assert.AreEqual(sampleValue, codec.Read(codedInput)); + Assert.IsTrue(codedInput.IsAtEnd); + } + + public void TestCalculateSizeWithTag() + { + var stream = new MemoryStream(); + var codedOutput = new CodedOutputStream(stream); + codec.WriteTagAndValue(codedOutput, sampleValue); + codedOutput.Flush(); + Assert.AreEqual(stream.Position, codec.CalculateSizeWithTag(sampleValue)); + } + + public void TestDefaultValue() + { + // WriteTagAndValue ignores default values + var stream = new MemoryStream(); + var codedOutput = new CodedOutputStream(stream); + codec.WriteTagAndValue(codedOutput, codec.DefaultValue); + codedOutput.Flush(); + Assert.AreEqual(0, stream.Position); + Assert.AreEqual(0, codec.CalculateSizeWithTag(codec.DefaultValue)); + if (typeof(T).IsValueType) + { + Assert.AreEqual(default(T), codec.DefaultValue); + } + + // The plain ValueWriter/ValueReader delegates don't. + if (codec.DefaultValue != null) // This part isn't appropriate for message types. + { + codedOutput = new CodedOutputStream(stream); + codec.ValueWriter(codedOutput, codec.DefaultValue); + codedOutput.Flush(); + Assert.AreNotEqual(0, stream.Position); + Assert.AreEqual(stream.Position, codec.ValueSizeCalculator(codec.DefaultValue)); + stream.Position = 0; + var codedInput = new CodedInputStream(stream); + Assert.AreEqual(codec.DefaultValue, codec.ValueReader(codedInput)); + } + } + + public void TestFixedSize() + { + Assert.AreEqual(name.Contains("Fixed"), codec.FixedSize != 0); + } + + public override string ToString() + { + return name; + } + } + } +} diff --git a/csharp/src/Google.Protobuf.Test/GeneratedMessageTest.cs b/csharp/src/Google.Protobuf.Test/GeneratedMessageTest.cs new file mode 100644 index 0000000000000..575d4586d90c9 --- /dev/null +++ b/csharp/src/Google.Protobuf.Test/GeneratedMessageTest.cs @@ -0,0 +1,655 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using System; +using System.IO; +using Google.Protobuf.TestProtos; +using NUnit.Framework; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using Google.Protobuf.WellKnownTypes; + +namespace Google.Protobuf +{ + /// + /// Tests around the generated TestAllTypes message. + /// + public class GeneratedMessageTest + { + [Test] + public void EmptyMessageFieldDistinctFromMissingMessageField() + { + // This demonstrates what we're really interested in... + var message1 = new TestAllTypes { SingleForeignMessage = new ForeignMessage() }; + var message2 = new TestAllTypes(); // SingleForeignMessage is null + EqualityTester.AssertInequality(message1, message2); + } + + [Test] + 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 NullStringAndBytesRejected() + { + var message = new TestAllTypes(); + Assert.Throws(() => message.SingleString = null); + Assert.Throws(() => message.OneofString = null); + Assert.Throws(() => message.SingleBytes = null); + Assert.Throws(() => message.OneofBytes = null); + } + + [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(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(1, 2, 3, 4), ByteString.CopyFrom(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); + } + + // Note that not every map within map_unittest_proto3 is used. They all go through very + // similar code paths. The fact that all maps are present is validation that we have codecs + // for every type. + [Test] + public void RoundTrip_Maps() + { + var message = new TestMap + { + MapBoolBool = { + { false, true }, + { true, false } + }, + MapInt32Bytes = { + { 5, ByteString.CopyFrom(6, 7, 8) }, + { 25, ByteString.CopyFrom(1, 2, 3, 4, 5) }, + { 10, ByteString.Empty } + }, + MapInt32ForeignMessage = { + { 0, new ForeignMessage { C = 10 } }, + { 5, null }, + }, + MapInt32Enum = { + { 1, MapEnum.MAP_ENUM_BAR }, + { 2000, MapEnum.MAP_ENUM_FOO } + } + }; + + byte[] bytes = message.ToByteArray(); + TestMap parsed = TestMap.Parser.ParseFrom(bytes); + Assert.AreEqual(message, parsed); + } + + [Test] + public void MapWithEmptyEntry() + { + var message = new TestMap + { + MapInt32Bytes = { { 0, ByteString.Empty } } + }; + + byte[] bytes = message.ToByteArray(); + Assert.AreEqual(2, bytes.Length); // Tag for field entry (1 byte), length of entry (0; 1 byte) + + var parsed = TestMap.Parser.ParseFrom(bytes); + Assert.AreEqual(1, parsed.MapInt32Bytes.Count); + Assert.AreEqual(ByteString.Empty, parsed.MapInt32Bytes[0]); + } + + [Test] + public void MapWithOnlyValue() + { + // Hand-craft the stream to contain a single entry with just a value. + var memoryStream = new MemoryStream(); + var output = new CodedOutputStream(memoryStream); + output.WriteTag(TestMap.MapInt32ForeignMessageFieldNumber, WireFormat.WireType.LengthDelimited); + var nestedMessage = new ForeignMessage { C = 20 }; + // Size of the entry (tag, size written by WriteMessage, data written by WriteMessage) + output.WriteLength(2 + nestedMessage.CalculateSize()); + output.WriteTag(2, WireFormat.WireType.LengthDelimited); + output.WriteMessage(nestedMessage); + output.Flush(); + + var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray()); + Assert.AreEqual(nestedMessage, parsed.MapInt32ForeignMessage[0]); + } + + [Test] + public void MapIgnoresExtraFieldsWithinEntryMessages() + { + // Hand-craft the stream to contain a single entry with three fields + var memoryStream = new MemoryStream(); + var output = new CodedOutputStream(memoryStream); + + output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); + + var key = 10; // Field 1 + var value = 20; // Field 2 + var extra = 30; // Field 3 + + // Each field can be represented in a single byte, with a single byte tag. + // Total message size: 6 bytes. + output.WriteLength(6); + output.WriteTag(1, WireFormat.WireType.Varint); + output.WriteInt32(key); + output.WriteTag(2, WireFormat.WireType.Varint); + output.WriteInt32(value); + output.WriteTag(3, WireFormat.WireType.Varint); + output.WriteInt32(extra); + output.Flush(); + + var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray()); + Assert.AreEqual(value, parsed.MapInt32Int32[key]); + } + + [Test] + public void MapFieldOrderIsIrrelevant() + { + var memoryStream = new MemoryStream(); + var output = new CodedOutputStream(memoryStream); + + output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); + + var key = 10; + var value = 20; + + // Each field can be represented in a single byte, with a single byte tag. + // Total message size: 4 bytes. + output.WriteLength(4); + output.WriteTag(2, WireFormat.WireType.Varint); + output.WriteInt32(value); + output.WriteTag(1, WireFormat.WireType.Varint); + output.WriteInt32(key); + output.Flush(); + + var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray()); + Assert.AreEqual(value, parsed.MapInt32Int32[key]); + } + + [Test] + public void MapNonContiguousEntries() + { + var memoryStream = new MemoryStream(); + var output = new CodedOutputStream(memoryStream); + + // Message structure: + // Entry for MapInt32Int32 + // Entry for MapStringString + // Entry for MapInt32Int32 + + // First entry + var key1 = 10; + var value1 = 20; + output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); + output.WriteLength(4); + output.WriteTag(1, WireFormat.WireType.Varint); + output.WriteInt32(key1); + output.WriteTag(2, WireFormat.WireType.Varint); + output.WriteInt32(value1); + + // Second entry + var key2 = "a"; + var value2 = "b"; + output.WriteTag(TestMap.MapStringStringFieldNumber, WireFormat.WireType.LengthDelimited); + output.WriteLength(6); // 3 bytes per entry: tag, size, character + output.WriteTag(1, WireFormat.WireType.LengthDelimited); + output.WriteString(key2); + output.WriteTag(2, WireFormat.WireType.LengthDelimited); + output.WriteString(value2); + + // Third entry + var key3 = 15; + var value3 = 25; + output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); + output.WriteLength(4); + output.WriteTag(1, WireFormat.WireType.Varint); + output.WriteInt32(key3); + output.WriteTag(2, WireFormat.WireType.Varint); + output.WriteInt32(value3); + + output.Flush(); + var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray()); + var expected = new TestMap + { + MapInt32Int32 = { { key1, value1 }, { key3, value3 } }, + MapStringString = { { key2, value2 } } + }; + Assert.AreEqual(expected, parsed); + } + + [Test] + public void DuplicateKeys_LastEntryWins() + { + var memoryStream = new MemoryStream(); + var output = new CodedOutputStream(memoryStream); + + var key = 10; + var value1 = 20; + var value2 = 30; + + // First entry + output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); + output.WriteLength(4); + output.WriteTag(1, WireFormat.WireType.Varint); + output.WriteInt32(key); + output.WriteTag(2, WireFormat.WireType.Varint); + output.WriteInt32(value1); + + // Second entry - same key, different value + output.WriteTag(TestMap.MapInt32Int32FieldNumber, WireFormat.WireType.LengthDelimited); + output.WriteLength(4); + output.WriteTag(1, WireFormat.WireType.Varint); + output.WriteInt32(key); + output.WriteTag(2, WireFormat.WireType.Varint); + output.WriteInt32(value2); + output.Flush(); + + var parsed = TestMap.Parser.ParseFrom(memoryStream.ToArray()); + Assert.AreEqual(value2, parsed.MapInt32Int32[key]); + } + + [Test] + public void CloneSingleNonMessageValues() + { + var original = new TestAllTypes + { + SingleBool = true, + SingleBytes = ByteString.CopyFrom(1, 2, 3, 4), + SingleDouble = 23.5, + SingleFixed32 = 23, + SingleFixed64 = 1234567890123, + SingleFloat = 12.25f, + SingleInt32 = 100, + SingleInt64 = 3210987654321, + SingleNestedEnum = TestAllTypes.Types.NestedEnum.FOO, + SingleSfixed32 = -123, + SingleSfixed64 = -12345678901234, + SingleSint32 = -456, + SingleSint64 = -12345678901235, + SingleString = "test", + SingleUint32 = uint.MaxValue, + SingleUint64 = ulong.MaxValue + }; + var clone = original.Clone(); + Assert.AreNotSame(original, clone); + Assert.AreEqual(original, clone); + // Just as a single example + clone.SingleInt32 = 150; + Assert.AreNotEqual(original, clone); + } + + [Test] + public void CloneRepeatedNonMessageValues() + { + var original = new TestAllTypes + { + RepeatedBool = { true, false }, + RepeatedBytes = { ByteString.CopyFrom(1, 2, 3, 4), ByteString.CopyFrom(5, 6) }, + RepeatedDouble = { -12.25, 23.5 }, + RepeatedFixed32 = { uint.MaxValue, 23 }, + RepeatedFixed64 = { ulong.MaxValue, 1234567890123 }, + RepeatedFloat = { 100f, 12.25f }, + RepeatedInt32 = { 100, 200 }, + RepeatedInt64 = { 3210987654321, long.MaxValue }, + RepeatedNestedEnum = { TestAllTypes.Types.NestedEnum.FOO, TestAllTypes.Types.NestedEnum.NEG }, + 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 } + }; + + var clone = original.Clone(); + Assert.AreNotSame(original, clone); + Assert.AreEqual(original, clone); + // Just as a single example + clone.RepeatedDouble.Add(25.5); + Assert.AreNotEqual(original, clone); + } + + [Test] + public void CloneSingleMessageField() + { + var original = new TestAllTypes + { + SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 20 } + }; + + var clone = original.Clone(); + Assert.AreNotSame(original, clone); + Assert.AreNotSame(original.SingleNestedMessage, clone.SingleNestedMessage); + Assert.AreEqual(original, clone); + + clone.SingleNestedMessage.Bb = 30; + Assert.AreNotEqual(original, clone); + } + + [Test] + public void CloneRepeatedMessageField() + { + var original = new TestAllTypes + { + RepeatedNestedMessage = { new TestAllTypes.Types.NestedMessage { Bb = 20 } } + }; + + var clone = original.Clone(); + Assert.AreNotSame(original, clone); + Assert.AreNotSame(original.RepeatedNestedMessage, clone.RepeatedNestedMessage); + Assert.AreNotSame(original.RepeatedNestedMessage[0], clone.RepeatedNestedMessage[0]); + Assert.AreEqual(original, clone); + + clone.RepeatedNestedMessage[0].Bb = 30; + Assert.AreNotEqual(original, clone); + } + + [Test] + public void CloneOneofField() + { + var original = new TestAllTypes + { + OneofNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 20 } + }; + + var clone = original.Clone(); + Assert.AreNotSame(original, clone); + Assert.AreEqual(original, clone); + + // We should have cloned the message + original.OneofNestedMessage.Bb = 30; + Assert.AreNotEqual(original, clone); + } + + [Test] + public void OneofProperties() + { + // Switch the oneof case between each of the different options, and check everything behaves + // as expected in each case. + var message = new TestAllTypes(); + Assert.AreEqual("", message.OneofString); + Assert.AreEqual(0, message.OneofUint32); + Assert.AreEqual(ByteString.Empty, message.OneofBytes); + Assert.IsNull(message.OneofNestedMessage); + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.None, message.OneofFieldCase); + + message.OneofString = "sample"; + Assert.AreEqual("sample", message.OneofString); + Assert.AreEqual(0, message.OneofUint32); + Assert.AreEqual(ByteString.Empty, message.OneofBytes); + Assert.IsNull(message.OneofNestedMessage); + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofString, message.OneofFieldCase); + + var bytes = ByteString.CopyFrom(1, 2, 3); + message.OneofBytes = bytes; + Assert.AreEqual("", message.OneofString); + Assert.AreEqual(0, message.OneofUint32); + Assert.AreEqual(bytes, message.OneofBytes); + Assert.IsNull(message.OneofNestedMessage); + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofBytes, message.OneofFieldCase); + + message.OneofUint32 = 20; + Assert.AreEqual("", message.OneofString); + Assert.AreEqual(20, message.OneofUint32); + Assert.AreEqual(ByteString.Empty, message.OneofBytes); + Assert.IsNull(message.OneofNestedMessage); + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, message.OneofFieldCase); + + var nestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 25 }; + message.OneofNestedMessage = nestedMessage; + Assert.AreEqual("", message.OneofString); + Assert.AreEqual(0, message.OneofUint32); + Assert.AreEqual(ByteString.Empty, message.OneofBytes); + Assert.AreEqual(nestedMessage, message.OneofNestedMessage); + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofNestedMessage, message.OneofFieldCase); + + message.ClearOneofField(); + Assert.AreEqual("", message.OneofString); + Assert.AreEqual(0, message.OneofUint32); + Assert.AreEqual(ByteString.Empty, message.OneofBytes); + Assert.IsNull(message.OneofNestedMessage); + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.None, message.OneofFieldCase); + } + + [Test] + public void OneofSerialization_NonDefaultValue() + { + var message = new TestAllTypes(); + message.OneofString = "this would take a bit of space"; + message.OneofUint32 = 10; + var bytes = message.ToByteArray(); + Assert.AreEqual(3, bytes.Length); // 2 bytes for the tag + 1 for the value - no string! + + var message2 = TestAllTypes.Parser.ParseFrom(bytes); + Assert.AreEqual(message, message2); + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, message2.OneofFieldCase); + } + + [Test] + public void OneofSerialization_DefaultValue() + { + var message = new TestAllTypes(); + message.OneofString = "this would take a bit of space"; + message.OneofUint32 = 0; // This is the default value for UInt32; normally wouldn't be serialized + var bytes = message.ToByteArray(); + Assert.AreEqual(3, bytes.Length); // 2 bytes for the tag + 1 for the value - it's still serialized + + var message2 = TestAllTypes.Parser.ParseFrom(bytes); + Assert.AreEqual(message, message2); + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, message2.OneofFieldCase); + } + + [Test] + public void IgnoreUnknownFields_RealDataStillRead() + { + var message = SampleMessages.CreateFullTestAllTypes(); + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + var unusedFieldNumber = 23456; + Assert.IsFalse(TestAllTypes.Descriptor.Fields.InDeclarationOrder().Select(x => x.FieldNumber).Contains(unusedFieldNumber)); + output.WriteTag(unusedFieldNumber, WireFormat.WireType.LengthDelimited); + output.WriteString("ignore me"); + message.WriteTo(output); + output.Flush(); + + stream.Position = 0; + var parsed = TestAllTypes.Parser.ParseFrom(stream); + Assert.AreEqual(message, parsed); + } + + [Test] + public void IgnoreUnknownFields_AllTypes() + { + // Simple way of ensuring we can skip all kinds of fields. + var data = SampleMessages.CreateFullTestAllTypes().ToByteArray(); + var empty = Empty.Parser.ParseFrom(data); + Assert.AreEqual(new Empty(), empty); + } + + // This was originally seen as a conformance test failure. + [Test] + public void TruncatedMessageFieldThrows() + { + // 130, 3 is the message tag + // 1 is the data length - but there's no data. + var data = new byte[] { 130, 3, 1 }; + Assert.Throws(() => TestAllTypes.Parser.ParseFrom(data)); + } + + /// + /// Demonstrates current behaviour with an extraneous end group tag - see issue 688 + /// for details; we may want to change this. + /// + [Test] + public void ExtraEndGroupSkipped() + { + var message = SampleMessages.CreateFullTestAllTypes(); + var stream = new MemoryStream(); + var output = new CodedOutputStream(stream); + + output.WriteTag(100, WireFormat.WireType.EndGroup); + output.WriteTag(TestAllTypes.SingleFixed32FieldNumber, WireFormat.WireType.Fixed32); + output.WriteFixed32(123); + + output.Flush(); + + stream.Position = 0; + var parsed = TestAllTypes.Parser.ParseFrom(stream); + Assert.AreEqual(new TestAllTypes { SingleFixed32 = 123 }, parsed); + } + } +} diff --git a/csharp/src/ProtocolBuffersLite.Test/ProtocolBuffersLite.Test.csproj b/csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj similarity index 59% rename from csharp/src/ProtocolBuffersLite.Test/ProtocolBuffersLite.Test.csproj rename to csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj index 4d813f83c47cd..d9593828e336b 100644 --- a/csharp/src/ProtocolBuffersLite.Test/ProtocolBuffersLite.Test.csproj +++ b/csharp/src/Google.Protobuf.Test/Google.Protobuf.Test.csproj @@ -5,15 +5,13 @@ AnyCPU 9.0.30729 2.0 - {EE01ED24-3750-4567-9A23-1DB676A15610} + {DD01ED24-3750-4567-9A23-1DB676A15610} Library Properties - Google.ProtocolBuffers - Google.ProtocolBuffersLite.Test + Google.Protobuf + Google.Protobuf.Test v4.5 512 - true - ..\..\keys\Google.ProtocolBuffers.snk 3.5 @@ -45,6 +43,20 @@ Off false + + pdbonly + true + bin\ReleaseSigned + obj\ReleaseSigned\ + TRACE;$(EnvironmentFlavor);$(EnvironmentTemplate) + prompt + 4 + true + Off + false + True + C:\keys\Google.Protobuf.snk + @@ -71,37 +83,49 @@ - - Properties\AssemblyInfo.cs - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - {E067A59D-9D0A-4A1F-92B1-38E4457241D1} - ProtocolBuffersLite.Serialization - - - {6969BDCE-D925-43F3-94AC-A531E6DF2591} - ProtocolBuffersLite - True + + {6908BDCE-D925-43F3-94AC-A531E6DF2591} + Google.Protobuf - + - + + + \ No newline at end of file diff --git a/csharp/src/Google.Protobuf/Google.Protobuf.nuspec b/csharp/src/Google.Protobuf/Google.Protobuf.nuspec new file mode 100644 index 0000000000000..228457a3e6d42 --- /dev/null +++ b/csharp/src/Google.Protobuf/Google.Protobuf.nuspec @@ -0,0 +1,36 @@ + + + + Google.Protobuf + Google Protocol Buffers C# + C# runtime library for Protocol Buffers - Google's data interchange format. + See project site for more info. + 3.0.0-alpha4 + Google Inc. + protobuf-packages + https://github.com/google/protobuf/blob/master/LICENSE + https://github.com/google/protobuf + false + C# proto3 support + Copyright 2015, Google Inc. + Protocol Buffers Binary Serialization Format Google proto proto3 + + + + + + + + + + + + + + + + + + + + diff --git a/csharp/src/ProtocolBuffers/DescriptorProtos/IDescriptorProto.cs b/csharp/src/Google.Protobuf/IDeepCloneable.cs similarity index 66% rename from csharp/src/ProtocolBuffers/DescriptorProtos/IDescriptorProto.cs rename to csharp/src/Google.Protobuf/IDeepCloneable.cs index c894d324c7010..c9c71bbe2c013 100644 --- a/csharp/src/ProtocolBuffers/DescriptorProtos/IDescriptorProto.cs +++ b/csharp/src/Google.Protobuf/IDeepCloneable.cs @@ -1,52 +1,54 @@ -// 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. -namespace Google.ProtocolBuffers.DescriptorProtos -{ - /// - /// Interface implemented by all DescriptorProtos. The generator doesn't - /// emit the interface implementation claim, so PartialClasses.cs contains - /// partial class declarations for each of them. - /// - /// The associated options protocol buffer type - public interface IDescriptorProto - { - /// - /// The brief name of the descriptor's target. - /// - string Name { get; } - - /// - /// The options for this descriptor. - /// - TOptions Options { get; } - } -} \ No newline at end of file +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +namespace Google.Protobuf +{ + /// + /// Generic interface for a deeply cloneable type. + /// + /// + /// + /// All generated messages implement this interface, but so do some non-message types. + /// Additionally, due to the type constraint on T in , + /// it is simpler to keep this as a separate interface. + /// + /// + /// The type itself, returned by the method. + public interface IDeepCloneable + { + /// + /// Creates a deep clone of this object. + /// + /// A deep clone of this object. + T Clone(); + } +} diff --git a/csharp/src/Google.Protobuf/IMessage.cs b/csharp/src/Google.Protobuf/IMessage.cs new file mode 100644 index 0000000000000..d089f9463985a --- /dev/null +++ b/csharp/src/Google.Protobuf/IMessage.cs @@ -0,0 +1,87 @@ +#region Copyright notice and license +// 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. +#endregion + +using System; +using Google.Protobuf.Reflection; + +namespace Google.Protobuf +{ + /// + /// 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(); + + /// + /// Descriptor for this message. All instances are expected to return the same descriptor, + /// and for generated types this will be an explicitly-implemented member, returning the + /// same value as the static property declared on the type. + /// + MessageDescriptor Descriptor { get; } + } + + /// + /// 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, IEquatable, IDeepCloneable 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); + } +} diff --git a/csharp/src/ProtocolBuffers/InvalidProtocolBufferException.cs b/csharp/src/Google.Protobuf/InvalidProtocolBufferException.cs similarity index 85% rename from csharp/src/ProtocolBuffers/InvalidProtocolBufferException.cs rename to csharp/src/Google.Protobuf/InvalidProtocolBufferException.cs index 67d7b374ab8ec..01d5539576edb 100644 --- a/csharp/src/ProtocolBuffers/InvalidProtocolBufferException.cs +++ b/csharp/src/Google.Protobuf/InvalidProtocolBufferException.cs @@ -1,10 +1,7 @@ #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/ +// 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 @@ -31,12 +28,11 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - #endregion using System.IO; -namespace Google.ProtocolBuffers +namespace Google.Protobuf { /// /// Thrown when a protocol message being parsed is invalid in some way, @@ -49,7 +45,13 @@ internal InvalidProtocolBufferException(string message) { } - public static InvalidProtocolBufferException TruncatedMessage() + internal static InvalidProtocolBufferException MoreDataAvailable() + { + return new InvalidProtocolBufferException( + "Completed reading a message while more data was available in the stream."); + } + + internal static InvalidProtocolBufferException TruncatedMessage() { return new InvalidProtocolBufferException( "While parsing a protocol message, the input ended unexpectedly " + @@ -65,13 +67,16 @@ internal static InvalidProtocolBufferException NegativeSize() "which claimed to have negative size."); } - public static InvalidProtocolBufferException MalformedVarint() + internal static InvalidProtocolBufferException MalformedVarint() { return new InvalidProtocolBufferException( "CodedInputStream encountered a malformed varint."); } - public static InvalidProtocolBufferException InvalidTag() + /// + /// Creates an exception for an error condition of an invalid tag being encountered. + /// + internal static InvalidProtocolBufferException InvalidTag() { return new InvalidProtocolBufferException( "Protocol message contained an invalid tag (zero)."); @@ -83,12 +88,6 @@ internal static InvalidProtocolBufferException InvalidEndTag() "Protocol message end-group tag did not match expected tag."); } - internal static InvalidProtocolBufferException InvalidWireType() - { - return new InvalidProtocolBufferException( - "Protocol message tag had invalid wire type."); - } - internal static InvalidProtocolBufferException RecursionLimitExceeded() { return new InvalidProtocolBufferException( diff --git a/csharp/src/Google.Protobuf/JsonFormatter.cs b/csharp/src/Google.Protobuf/JsonFormatter.cs new file mode 100644 index 0000000000000..12bbdfdde921c --- /dev/null +++ b/csharp/src/Google.Protobuf/JsonFormatter.cs @@ -0,0 +1,788 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using System; +using System.Collections; +using System.Globalization; +using System.Text; +using Google.Protobuf.Reflection; +using Google.Protobuf.WellKnownTypes; +using System.Linq; + +namespace Google.Protobuf +{ + /// + /// Reflection-based converter from messages to JSON. + /// + /// + /// + /// Instances of this class are thread-safe, with no mutable state. + /// + /// + /// This is a simple start to get JSON formatting working. As it's reflection-based, + /// it's not as quick as baking calls into generated messages - but is a simpler implementation. + /// (This code is generally not heavily optimized.) + /// + /// + public sealed class JsonFormatter + { + private static JsonFormatter defaultInstance = new JsonFormatter(Settings.Default); + + /// + /// Returns a formatter using the default settings. + /// + public static JsonFormatter Default { get { return defaultInstance; } } + + /// + /// The JSON representation of the first 160 characters of Unicode. + /// Empty strings are replaced by the static constructor. + /// + private static readonly string[] CommonRepresentations = { + // C0 (ASCII and derivatives) control characters + "\\u0000", "\\u0001", "\\u0002", "\\u0003", // 0x00 + "\\u0004", "\\u0005", "\\u0006", "\\u0007", + "\\b", "\\t", "\\n", "\\u000b", + "\\f", "\\r", "\\u000e", "\\u000f", + "\\u0010", "\\u0011", "\\u0012", "\\u0013", // 0x10 + "\\u0014", "\\u0015", "\\u0016", "\\u0017", + "\\u0018", "\\u0019", "\\u001a", "\\u001b", + "\\u001c", "\\u001d", "\\u001e", "\\u001f", + // Escaping of " and \ are required by www.json.org string definition. + // Escaping of < and > are required for HTML security. + "", "", "\\\"", "", "", "", "", "", // 0x20 + "", "", "", "", "", "", "", "", + "", "", "", "", "", "", "", "", // 0x30 + "", "", "", "", "\\u003c", "", "\\u003e", "", + "", "", "", "", "", "", "", "", // 0x40 + "", "", "", "", "", "", "", "", + "", "", "", "", "", "", "", "", // 0x50 + "", "", "", "", "\\\\", "", "", "", + "", "", "", "", "", "", "", "", // 0x60 + "", "", "", "", "", "", "", "", + "", "", "", "", "", "", "", "", // 0x70 + "", "", "", "", "", "", "", "\\u007f", + // C1 (ISO 8859 and Unicode) extended control characters + "\\u0080", "\\u0081", "\\u0082", "\\u0083", // 0x80 + "\\u0084", "\\u0085", "\\u0086", "\\u0087", + "\\u0088", "\\u0089", "\\u008a", "\\u008b", + "\\u008c", "\\u008d", "\\u008e", "\\u008f", + "\\u0090", "\\u0091", "\\u0092", "\\u0093", // 0x90 + "\\u0094", "\\u0095", "\\u0096", "\\u0097", + "\\u0098", "\\u0099", "\\u009a", "\\u009b", + "\\u009c", "\\u009d", "\\u009e", "\\u009f" + }; + + static JsonFormatter() + { + for (int i = 0; i < CommonRepresentations.Length; i++) + { + if (CommonRepresentations[i] == "") + { + CommonRepresentations[i] = ((char) i).ToString(); + } + } + } + + private readonly Settings settings; + + /// + /// Creates a new formatted with the given settings. + /// + /// The settings. + public JsonFormatter(Settings settings) + { + this.settings = settings; + } + + /// + /// Formats the specified message as JSON. + /// + /// The message to format. + /// The formatted message. + public string Format(IMessage message) + { + Preconditions.CheckNotNull(message, "message"); + StringBuilder builder = new StringBuilder(); + if (message.Descriptor.IsWellKnownType) + { + WriteWellKnownTypeValue(builder, message.Descriptor, message, false); + } + else + { + WriteMessage(builder, message); + } + return builder.ToString(); + } + + private void WriteMessage(StringBuilder builder, IMessage message) + { + if (message == null) + { + WriteNull(builder); + return; + } + builder.Append("{ "); + var fields = message.Descriptor.Fields; + bool first = true; + // First non-oneof fields + foreach (var field in fields.InFieldNumberOrder()) + { + var accessor = field.Accessor; + // Oneofs are written later + if (field.ContainingOneof != null && field.ContainingOneof.Accessor.GetCaseFieldDescriptor(message) != field) + { + continue; + } + // Omit default values unless we're asked to format them, or they're oneofs (where the default + // value is still formatted regardless, because that's how we preserve the oneof case). + object value = accessor.GetValue(message); + if (field.ContainingOneof == null && !settings.FormatDefaultValues && IsDefaultValue(accessor, value)) + { + continue; + } + // Omit awkward (single) values such as unknown enum values + if (!field.IsRepeated && !field.IsMap && !CanWriteSingleValue(accessor.Descriptor, value)) + { + continue; + } + + // Okay, all tests complete: let's write the field value... + if (!first) + { + builder.Append(", "); + } + WriteString(builder, ToCamelCase(accessor.Descriptor.Name)); + builder.Append(": "); + WriteValue(builder, accessor, value); + first = false; + } + builder.Append(first ? "}" : " }"); + } + + // Converted from src/google/protobuf/util/internal/utility.cc ToCamelCase + internal static string ToCamelCase(string input) + { + bool capitalizeNext = false; + bool wasCap = true; + bool isCap = false; + bool firstWord = true; + StringBuilder result = new StringBuilder(input.Length); + + for (int i = 0; i < input.Length; i++, wasCap = isCap) + { + isCap = char.IsUpper(input[i]); + if (input[i] == '_') + { + capitalizeNext = true; + if (result.Length != 0) + { + firstWord = false; + } + continue; + } + else if (firstWord) + { + // Consider when the current character B is capitalized, + // first word ends when: + // 1) following a lowercase: "...aB..." + // 2) followed by a lowercase: "...ABc..." + if (result.Length != 0 && isCap && + (!wasCap || (i + 1 < input.Length && char.IsLower(input[i + 1])))) + { + firstWord = false; + } + else + { + result.Append(char.ToLowerInvariant(input[i])); + continue; + } + } + else if (capitalizeNext) + { + capitalizeNext = false; + if (char.IsLower(input[i])) + { + result.Append(char.ToUpperInvariant(input[i])); + continue; + } + } + result.Append(input[i]); + } + return result.ToString(); + } + + private static void WriteNull(StringBuilder builder) + { + builder.Append("null"); + } + + private static bool IsDefaultValue(IFieldAccessor accessor, object value) + { + if (accessor.Descriptor.IsMap) + { + IDictionary dictionary = (IDictionary) value; + return dictionary.Count == 0; + } + if (accessor.Descriptor.IsRepeated) + { + IList list = (IList) value; + return list.Count == 0; + } + switch (accessor.Descriptor.FieldType) + { + case FieldType.Bool: + return (bool) value == false; + case FieldType.Bytes: + return (ByteString) value == ByteString.Empty; + case FieldType.String: + return (string) value == ""; + case FieldType.Double: + return (double) value == 0.0; + case FieldType.SInt32: + case FieldType.Int32: + case FieldType.SFixed32: + case FieldType.Enum: + return (int) value == 0; + case FieldType.Fixed32: + case FieldType.UInt32: + return (uint) value == 0; + case FieldType.Fixed64: + case FieldType.UInt64: + return (ulong) value == 0; + case FieldType.SFixed64: + case FieldType.Int64: + case FieldType.SInt64: + return (long) value == 0; + case FieldType.Float: + return (float) value == 0f; + case FieldType.Message: + case FieldType.Group: // Never expect to get this, but... + return value == null; + default: + throw new ArgumentException("Invalid field type"); + } + } + + private void WriteValue(StringBuilder builder, IFieldAccessor accessor, object value) + { + if (accessor.Descriptor.IsMap) + { + WriteDictionary(builder, accessor, (IDictionary) value); + } + else if (accessor.Descriptor.IsRepeated) + { + WriteList(builder, accessor, (IList) value); + } + else + { + WriteSingleValue(builder, accessor.Descriptor, value); + } + } + + private void WriteSingleValue(StringBuilder builder, FieldDescriptor descriptor, object value) + { + switch (descriptor.FieldType) + { + case FieldType.Bool: + builder.Append((bool) value ? "true" : "false"); + break; + case FieldType.Bytes: + // Nothing in Base64 needs escaping + builder.Append('"'); + builder.Append(((ByteString) value).ToBase64()); + builder.Append('"'); + break; + case FieldType.String: + WriteString(builder, (string) value); + break; + case FieldType.Fixed32: + case FieldType.UInt32: + case FieldType.SInt32: + case FieldType.Int32: + case FieldType.SFixed32: + { + IFormattable formattable = (IFormattable) value; + builder.Append(formattable.ToString("d", CultureInfo.InvariantCulture)); + break; + } + case FieldType.Enum: + EnumValueDescriptor enumValue = descriptor.EnumType.FindValueByNumber((int) value); + // We will already have validated that this is a known value. + WriteString(builder, enumValue.Name); + break; + case FieldType.Fixed64: + case FieldType.UInt64: + case FieldType.SFixed64: + case FieldType.Int64: + case FieldType.SInt64: + { + builder.Append('"'); + IFormattable formattable = (IFormattable) value; + builder.Append(formattable.ToString("d", CultureInfo.InvariantCulture)); + builder.Append('"'); + break; + } + case FieldType.Double: + case FieldType.Float: + string text = ((IFormattable) value).ToString("r", CultureInfo.InvariantCulture); + if (text == "NaN" || text == "Infinity" || text == "-Infinity") + { + builder.Append('"'); + builder.Append(text); + builder.Append('"'); + } + else + { + builder.Append(text); + } + break; + case FieldType.Message: + case FieldType.Group: // Never expect to get this, but... + if (descriptor.MessageType.IsWellKnownType) + { + WriteWellKnownTypeValue(builder, descriptor.MessageType, value, true); + } + else + { + WriteMessage(builder, (IMessage) value); + } + break; + default: + throw new ArgumentException("Invalid field type: " + descriptor.FieldType); + } + } + + /// + /// Central interception point for well-known type formatting. Any well-known types which + /// don't need special handling can fall back to WriteMessage. We avoid assuming that the + /// values are using the embedded well-known types, in order to allow for dynamic messages + /// in the future. + /// + private void WriteWellKnownTypeValue(StringBuilder builder, MessageDescriptor descriptor, object value, bool inField) + { + if (value == null) + { + WriteNull(builder); + return; + } + // For wrapper types, the value will be the (possibly boxed) "native" value, + // so we can write it as if we were unconditionally writing the Value field for the wrapper type. + if (descriptor.File == Int32Value.Descriptor.File) + { + WriteSingleValue(builder, descriptor.FindFieldByNumber(1), value); + return; + } + if (descriptor.FullName == Timestamp.Descriptor.FullName) + { + MaybeWrapInString(builder, value, WriteTimestamp, inField); + return; + } + if (descriptor.FullName == Duration.Descriptor.FullName) + { + MaybeWrapInString(builder, value, WriteDuration, inField); + return; + } + if (descriptor.FullName == FieldMask.Descriptor.FullName) + { + MaybeWrapInString(builder, value, WriteFieldMask, inField); + return; + } + if (descriptor.FullName == Struct.Descriptor.FullName) + { + WriteStruct(builder, (IMessage) value); + return; + } + if (descriptor.FullName == ListValue.Descriptor.FullName) + { + var fieldAccessor = descriptor.Fields[ListValue.ValuesFieldNumber].Accessor; + WriteList(builder, fieldAccessor, (IList) fieldAccessor.GetValue((IMessage) value)); + return; + } + if (descriptor.FullName == Value.Descriptor.FullName) + { + WriteStructFieldValue(builder, (IMessage) value); + return; + } + WriteMessage(builder, (IMessage) value); + } + + /// + /// Some well-known types end up as string values... so they need wrapping in quotes, but only + /// when they're being used as fields within another message. + /// + private void MaybeWrapInString(StringBuilder builder, object value, Action action, bool inField) + { + if (inField) + { + builder.Append('"'); + action(builder, (IMessage) value); + builder.Append('"'); + } + else + { + action(builder, (IMessage) value); + } + } + + private void WriteTimestamp(StringBuilder builder, IMessage value) + { + // TODO: In the common case where this *is* using the built-in Timestamp type, we could + // avoid all the reflection at this point, by casting to Timestamp. In the interests of + // avoiding subtle bugs, don't do that until we've implemented DynamicMessage so that we can prove + // it still works in that case. + int nanos = (int) value.Descriptor.Fields[Timestamp.NanosFieldNumber].Accessor.GetValue(value); + long seconds = (long) value.Descriptor.Fields[Timestamp.SecondsFieldNumber].Accessor.GetValue(value); + + // Even if the original message isn't using the built-in classes, we can still build one... and then + // rely on it being normalized. + Timestamp normalized = Timestamp.Normalize(seconds, nanos); + // Use .NET's formatting for the value down to the second, including an opening double quote (as it's a string value) + DateTime dateTime = normalized.ToDateTime(); + builder.Append(dateTime.ToString("yyyy'-'MM'-'dd'T'HH:mm:ss", CultureInfo.InvariantCulture)); + AppendNanoseconds(builder, Math.Abs(normalized.Nanos)); + builder.Append('Z'); + } + + private void WriteDuration(StringBuilder builder, IMessage value) + { + // TODO: Same as for WriteTimestamp + int nanos = (int) value.Descriptor.Fields[Duration.NanosFieldNumber].Accessor.GetValue(value); + long seconds = (long) value.Descriptor.Fields[Duration.SecondsFieldNumber].Accessor.GetValue(value); + + // Even if the original message isn't using the built-in classes, we can still build one... and then + // rely on it being normalized. + Duration normalized = Duration.Normalize(seconds, nanos); + + // The seconds part will normally provide the minus sign if we need it, but not if it's 0... + if (normalized.Seconds == 0 && normalized.Nanos < 0) + { + builder.Append('-'); + } + + builder.Append(normalized.Seconds.ToString("d", CultureInfo.InvariantCulture)); + AppendNanoseconds(builder, Math.Abs(normalized.Nanos)); + builder.Append('s'); + } + + private void WriteFieldMask(StringBuilder builder, IMessage value) + { + IList paths = (IList) value.Descriptor.Fields[FieldMask.PathsFieldNumber].Accessor.GetValue(value); + AppendEscapedString(builder, string.Join(",", paths.Cast().Select(ToCamelCase))); + } + + /// + /// Appends a number of nanoseconds to a StringBuilder. Either 0 digits are added (in which + /// case no "." is appended), or 3 6 or 9 digits. + /// + private static void AppendNanoseconds(StringBuilder builder, int nanos) + { + if (nanos != 0) + { + builder.Append('.'); + // Output to 3, 6 or 9 digits. + if (nanos % 1000000 == 0) + { + builder.Append((nanos / 1000000).ToString("d", CultureInfo.InvariantCulture)); + } + else if (nanos % 1000 == 0) + { + builder.Append((nanos / 1000).ToString("d", CultureInfo.InvariantCulture)); + } + else + { + builder.Append(nanos.ToString("d", CultureInfo.InvariantCulture)); + } + } + } + + private void WriteStruct(StringBuilder builder, IMessage message) + { + builder.Append("{ "); + IDictionary fields = (IDictionary) message.Descriptor.Fields[Struct.FieldsFieldNumber].Accessor.GetValue(message); + bool first = true; + foreach (DictionaryEntry entry in fields) + { + string key = (string) entry.Key; + IMessage value = (IMessage) entry.Value; + if (string.IsNullOrEmpty(key) || value == null) + { + throw new InvalidOperationException("Struct fields cannot have an empty key or a null value."); + } + + if (!first) + { + builder.Append(", "); + } + WriteString(builder, key); + builder.Append(": "); + WriteStructFieldValue(builder, value); + first = false; + } + builder.Append(first ? "}" : " }"); + } + + private void WriteStructFieldValue(StringBuilder builder, IMessage message) + { + var specifiedField = message.Descriptor.Oneofs[0].Accessor.GetCaseFieldDescriptor(message); + if (specifiedField == null) + { + throw new InvalidOperationException("Value message must contain a value for the oneof."); + } + + object value = specifiedField.Accessor.GetValue(message); + + switch (specifiedField.FieldNumber) + { + case Value.BoolValueFieldNumber: + case Value.StringValueFieldNumber: + case Value.NumberValueFieldNumber: + WriteSingleValue(builder, specifiedField, value); + return; + case Value.StructValueFieldNumber: + case Value.ListValueFieldNumber: + // Structs and ListValues are nested messages, and already well-known types. + var nestedMessage = (IMessage) specifiedField.Accessor.GetValue(message); + WriteWellKnownTypeValue(builder, nestedMessage.Descriptor, nestedMessage, true); + return; + case Value.NullValueFieldNumber: + WriteNull(builder); + return; + default: + throw new InvalidOperationException("Unexpected case in struct field: " + specifiedField.FieldNumber); + } + } + + private void WriteList(StringBuilder builder, IFieldAccessor accessor, IList list) + { + builder.Append("[ "); + bool first = true; + foreach (var value in list) + { + if (!CanWriteSingleValue(accessor.Descriptor, value)) + { + continue; + } + if (!first) + { + builder.Append(", "); + } + WriteSingleValue(builder, accessor.Descriptor, value); + first = false; + } + builder.Append(first ? "]" : " ]"); + } + + private void WriteDictionary(StringBuilder builder, IFieldAccessor accessor, IDictionary dictionary) + { + builder.Append("{ "); + bool first = true; + FieldDescriptor keyType = accessor.Descriptor.MessageType.FindFieldByNumber(1); + FieldDescriptor valueType = accessor.Descriptor.MessageType.FindFieldByNumber(2); + // This will box each pair. Could use IDictionaryEnumerator, but that's ugly in terms of disposal. + foreach (DictionaryEntry pair in dictionary) + { + if (!CanWriteSingleValue(valueType, pair.Value)) + { + continue; + } + if (!first) + { + builder.Append(", "); + } + string keyText; + switch (keyType.FieldType) + { + case FieldType.String: + keyText = (string) pair.Key; + break; + case FieldType.Bool: + keyText = (bool) pair.Key ? "true" : "false"; + break; + case FieldType.Fixed32: + case FieldType.Fixed64: + case FieldType.SFixed32: + case FieldType.SFixed64: + case FieldType.Int32: + case FieldType.Int64: + case FieldType.SInt32: + case FieldType.SInt64: + case FieldType.UInt32: + case FieldType.UInt64: + keyText = ((IFormattable) pair.Key).ToString("d", CultureInfo.InvariantCulture); + break; + default: + throw new ArgumentException("Invalid key type: " + keyType.FieldType); + } + WriteString(builder, keyText); + builder.Append(": "); + WriteSingleValue(builder, valueType, pair.Value); + first = false; + } + builder.Append(first ? "}" : " }"); + } + + /// + /// Returns whether or not a singular value can be represented in JSON. + /// Currently only relevant for enums, where unknown values can't be represented. + /// For repeated/map fields, this always returns true. + /// + private bool CanWriteSingleValue(FieldDescriptor descriptor, object value) + { + if (descriptor.FieldType == FieldType.Enum) + { + EnumValueDescriptor enumValue = descriptor.EnumType.FindValueByNumber((int) value); + return enumValue != null; + } + return true; + } + + /// + /// Writes a string (including leading and trailing double quotes) to a builder, escaping as required. + /// + /// + /// Other than surrogate pair handling, this code is mostly taken from src/google/protobuf/util/internal/json_escaping.cc. + /// + private void WriteString(StringBuilder builder, string text) + { + builder.Append('"'); + AppendEscapedString(builder, text); + builder.Append('"'); + } + + /// + /// Appends the given text to the string builder, escaping as required. + /// + private void AppendEscapedString(StringBuilder builder, string text) + { + for (int i = 0; i < text.Length; i++) + { + char c = text[i]; + if (c < 0xa0) + { + builder.Append(CommonRepresentations[c]); + continue; + } + if (char.IsHighSurrogate(c)) + { + // Encountered first part of a surrogate pair. + // Check that we have the whole pair, and encode both parts as hex. + i++; + if (i == text.Length || !char.IsLowSurrogate(text[i])) + { + throw new ArgumentException("String contains low surrogate not followed by high surrogate"); + } + HexEncodeUtf16CodeUnit(builder, c); + HexEncodeUtf16CodeUnit(builder, text[i]); + continue; + } + else if (char.IsLowSurrogate(c)) + { + throw new ArgumentException("String contains high surrogate not preceded by low surrogate"); + } + switch ((uint) c) + { + // These are not required by json spec + // but used to prevent security bugs in javascript. + case 0xfeff: // Zero width no-break space + case 0xfff9: // Interlinear annotation anchor + case 0xfffa: // Interlinear annotation separator + case 0xfffb: // Interlinear annotation terminator + + case 0x00ad: // Soft-hyphen + case 0x06dd: // Arabic end of ayah + case 0x070f: // Syriac abbreviation mark + case 0x17b4: // Khmer vowel inherent Aq + case 0x17b5: // Khmer vowel inherent Aa + HexEncodeUtf16CodeUnit(builder, c); + break; + + default: + if ((c >= 0x0600 && c <= 0x0603) || // Arabic signs + (c >= 0x200b && c <= 0x200f) || // Zero width etc. + (c >= 0x2028 && c <= 0x202e) || // Separators etc. + (c >= 0x2060 && c <= 0x2064) || // Invisible etc. + (c >= 0x206a && c <= 0x206f)) + { + HexEncodeUtf16CodeUnit(builder, c); + } + else + { + // No handling of surrogates here - that's done earlier + builder.Append(c); + } + break; + } + } + } + + private const string Hex = "0123456789abcdef"; + private static void HexEncodeUtf16CodeUnit(StringBuilder builder, char c) + { + builder.Append("\\u"); + builder.Append(Hex[(c >> 12) & 0xf]); + builder.Append(Hex[(c >> 8) & 0xf]); + builder.Append(Hex[(c >> 4) & 0xf]); + builder.Append(Hex[(c >> 0) & 0xf]); + } + + /// + /// Settings controlling JSON formatting. + /// + public sealed class Settings + { + private static readonly Settings defaultInstance = new Settings(false); + + /// + /// Default settings, as used by + /// + public static Settings Default { get { return defaultInstance; } } + + private readonly bool formatDefaultValues; + + + /// + /// Whether fields whose values are the default for the field type (e.g. 0 for integers) + /// should be formatted (true) or omitted (false). + /// + public bool FormatDefaultValues { get { return formatDefaultValues; } } + + /// + /// Creates a new object with the specified formatting of default values. + /// + /// true if default values (0, empty strings etc) should be formatted; false otherwise. + public Settings(bool formatDefaultValues) + { + this.formatDefaultValues = formatDefaultValues; + } + } + } +} diff --git a/csharp/src/Google.Protobuf/LimitedInputStream.cs b/csharp/src/Google.Protobuf/LimitedInputStream.cs new file mode 100644 index 0000000000000..f11d19d944060 --- /dev/null +++ b/csharp/src/Google.Protobuf/LimitedInputStream.cs @@ -0,0 +1,110 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using System; +using System.IO; + +namespace Google.Protobuf +{ + /// + /// Stream implementation which proxies another stream, only allowing a certain amount + /// of data to be read. Note that this is only used to read delimited streams, so it + /// doesn't attempt to implement everything. + /// + internal sealed class LimitedInputStream : Stream + { + private readonly Stream proxied; + private int bytesLeft; + + internal LimitedInputStream(Stream proxied, int size) + { + this.proxied = proxied; + bytesLeft = size; + } + + public override bool CanRead + { + get { return true; } + } + + public override bool CanSeek + { + get { return false; } + } + + public override bool CanWrite + { + get { return false; } + } + + public override void Flush() + { + } + + public override long Length + { + get { throw new NotSupportedException(); } + } + + public override long Position + { + get { throw new NotSupportedException(); } + set { throw new NotSupportedException(); } + } + + public override int Read(byte[] buffer, int offset, int count) + { + if (bytesLeft > 0) + { + int bytesRead = proxied.Read(buffer, offset, Math.Min(bytesLeft, count)); + bytesLeft -= bytesRead; + return bytesRead; + } + return 0; + } + + public override long Seek(long offset, SeekOrigin origin) + { + throw new NotSupportedException(); + } + + public override void SetLength(long value) + { + throw new NotSupportedException(); + } + + public override void Write(byte[] buffer, int offset, int count) + { + throw new NotSupportedException(); + } + } +} diff --git a/csharp/src/Google.Protobuf/MessageExtensions.cs b/csharp/src/Google.Protobuf/MessageExtensions.cs new file mode 100644 index 0000000000000..d2d057c0c9204 --- /dev/null +++ b/csharp/src/Google.Protobuf/MessageExtensions.cs @@ -0,0 +1,157 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using System.IO; + +namespace Google.Protobuf +{ + /// + /// Extension methods on and . + /// + public static class MessageExtensions + { + /// + /// Merges data from the given byte array into an existing message. + /// + /// The message to merge the data into. + /// The data to merge, which must be protobuf-encoded binary data. + public static void MergeFrom(this IMessage message, byte[] data) + { + Preconditions.CheckNotNull(message, "message"); + Preconditions.CheckNotNull(data, "data"); + CodedInputStream input = new CodedInputStream(data); + message.MergeFrom(input); + input.CheckReadEndOfStreamTag(); + } + + /// + /// Merges data from the given byte string into an existing message. + /// + /// The message to merge the data into. + /// The data to merge, which must be protobuf-encoded binary data. + public static void MergeFrom(this IMessage message, ByteString data) + { + Preconditions.CheckNotNull(message, "message"); + Preconditions.CheckNotNull(data, "data"); + CodedInputStream input = data.CreateCodedInput(); + message.MergeFrom(input); + input.CheckReadEndOfStreamTag(); + } + + /// + /// Merges data from the given stream into an existing message. + /// + /// The message to merge the data into. + /// Stream containing the data to merge, which must be protobuf-encoded binary data. + public static void MergeFrom(this IMessage message, Stream input) + { + Preconditions.CheckNotNull(message, "message"); + Preconditions.CheckNotNull(input, "input"); + CodedInputStream codedInput = new CodedInputStream(input); + message.MergeFrom(codedInput); + codedInput.CheckReadEndOfStreamTag(); + } + + /// + /// Merges length-delimited data from the given stream into an existing message. + /// + /// + /// The stream is expected to contain a length and then the data. Only the amount of data + /// specified by the length will be consumed. + /// + /// The message to merge the data into. + /// Stream containing the data to merge, which must be protobuf-encoded binary data. + public static void MergeDelimitedFrom(this IMessage message, Stream input) + { + Preconditions.CheckNotNull(message, "message"); + Preconditions.CheckNotNull(input, "input"); + int size = (int) CodedInputStream.ReadRawVarint32(input); + Stream limitedStream = new LimitedInputStream(input, size); + message.MergeFrom(limitedStream); + } + + /// + /// Converts the given message into a byte array in protobuf encoding. + /// + /// The message to convert. + /// The message data as a byte array. + public static byte[] ToByteArray(this IMessage message) + { + Preconditions.CheckNotNull(message, "message"); + byte[] result = new byte[message.CalculateSize()]; + CodedOutputStream output = new CodedOutputStream(result); + message.WriteTo(output); + output.CheckNoSpaceLeft(); + return result; + } + + /// + /// Writes the given message data to the given stream in protobuf encoding. + /// + /// The message to write to the stream. + /// The stream to write to. + public static void WriteTo(this IMessage message, Stream output) + { + Preconditions.CheckNotNull(message, "message"); + Preconditions.CheckNotNull(output, "output"); + CodedOutputStream codedOutput = new CodedOutputStream(output); + message.WriteTo(codedOutput); + codedOutput.Flush(); + } + + /// + /// Writes the length and then data of the given message to a stream. + /// + /// The message to write. + /// The output stream to write to. + public static void WriteDelimitedTo(this IMessage message, Stream output) + { + Preconditions.CheckNotNull(message, "message"); + Preconditions.CheckNotNull(output, "output"); + CodedOutputStream codedOutput = new CodedOutputStream(output); + codedOutput.WriteRawVarint32((uint)message.CalculateSize()); + message.WriteTo(codedOutput); + codedOutput.Flush(); + } + + /// + /// Converts the given message into a byte string in protobuf encoding. + /// + /// The message to convert. + /// The message data as a byte string. + public static ByteString ToByteString(this IMessage message) + { + Preconditions.CheckNotNull(message, "message"); + return ByteString.AttachBytes(message.ToByteArray()); + } + } +} diff --git a/csharp/src/Google.Protobuf/MessageParser.cs b/csharp/src/Google.Protobuf/MessageParser.cs new file mode 100644 index 0000000000000..6a6f101749478 --- /dev/null +++ b/csharp/src/Google.Protobuf/MessageParser.cs @@ -0,0 +1,146 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using System; +using System.IO; + +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. + /// + /// 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) + { + Preconditions.CheckNotNull(data, "data"); + T message = factory(); + message.MergeFrom(data); + return message; + } + + /// + /// Parses a message from the given byte string. + /// + /// The data to parse. + /// The parsed message. + public T ParseFrom(ByteString data) + { + Preconditions.CheckNotNull(data, "data"); + T message = factory(); + message.MergeFrom(data); + return message; + } + + /// + /// Parses a message from the given stream. + /// + /// The stream to parse. + /// The parsed message. + public T ParseFrom(Stream input) + { + T message = factory(); + message.MergeFrom(input); + return message; + } + + /// + /// Parses a length-delimited message from the given stream. + /// + /// + /// The stream is expected to contain a length and then the data. Only the amount of data + /// specified by the length will be consumed. + /// + /// The stream to parse. + /// The parsed message. + public T ParseDelimitedFrom(Stream input) + { + T message = factory(); + message.MergeDelimitedFrom(input); + return message; + } + + /// + /// Parses a message from the given coded input stream. + /// + /// The stream to parse. + /// The parsed message. + public T ParseFrom(CodedInputStream input) + { + T message = factory(); + message.MergeFrom(input); + return message; + } + } +} diff --git a/csharp/src/ProtocolBuffers/ThrowHelper.cs b/csharp/src/Google.Protobuf/Preconditions.cs similarity index 63% rename from csharp/src/ProtocolBuffers/ThrowHelper.cs rename to csharp/src/Google.Protobuf/Preconditions.cs index 69e5f569a7248..2db35ff63a730 100644 --- a/csharp/src/ProtocolBuffers/ThrowHelper.cs +++ b/csharp/src/Google.Protobuf/Preconditions.cs @@ -1,92 +1,74 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; - -namespace Google.ProtocolBuffers -{ - /// - /// Helper methods for throwing exceptions - /// - public static class ThrowHelper - { - /// - /// Throws an ArgumentNullException if the given value is null. - /// - public static void ThrowIfNull(object value, string name) - { - if (value == null) - { - throw new ArgumentNullException(name); - } - } - - /// - /// Throws an ArgumentNullException if the given value is null. - /// - public static void ThrowIfNull(object value) - { - if (value == null) - { - throw new ArgumentNullException(); - } - } - - /// - /// Throws an ArgumentNullException if the given value or any element within it is null. - /// - public static void ThrowIfAnyNull(IEnumerable sequence) - { - foreach (T t in sequence) - { - if (t == null) - { - throw new ArgumentNullException(); - } - } - } - - 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 - } - } +#region Copyright notice and license +// 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. +#endregion + +using System; + +namespace Google.Protobuf +{ + /// + /// Helper methods for throwing exceptions + /// + public static class Preconditions + { + /// + /// Throws an ArgumentNullException if the given value is null, otherwise + /// return the value to the caller. + /// + public static T CheckNotNull(T value, string name) where T : class + { + if (value == null) + { + throw new ArgumentNullException(name); + } + return value; + } + + /// + /// Throws an ArgumentNullException if the given value is null, otherwise + /// return the value to the caller. + /// + /// + /// This is equivalent to but without the type parameter + /// constraint. In most cases, the constraint is useful to prevent you from calling CheckNotNull + /// with a value type - but it gets in the way if either you want to use it with a nullable + /// value type, or you want to use it with an unconstrained type parameter. + /// + internal static T CheckNotNullUnconstrained(T value, string name) + { + if (value == null) + { + throw new ArgumentNullException(name); + } + return value; + } + } } \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers/Properties/AssemblyInfo.cs b/csharp/src/Google.Protobuf/Properties/AssemblyInfo.cs similarity index 67% rename from csharp/src/ProtocolBuffers/Properties/AssemblyInfo.cs rename to csharp/src/Google.Protobuf/Properties/AssemblyInfo.cs index 806bd5d5dfd17..9a484ad66a4e0 100644 --- a/csharp/src/ProtocolBuffers/Properties/AssemblyInfo.cs +++ b/csharp/src/Google.Protobuf/Properties/AssemblyInfo.cs @@ -1,8 +1,7 @@ +#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/ +// 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 @@ -29,39 +28,37 @@ // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -using System; +#endregion + using System.Reflection; -using System.Runtime.InteropServices; using System.Runtime.CompilerServices; +using System.Security; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. -using System.Security; -[assembly: AssemblyTitle("ProtocolBuffers")] +[assembly: AssemblyTitle("Google.Protobuf")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("ProtocolBuffers")] -[assembly: AssemblyCopyright("Copyright © 2008")] +[assembly: AssemblyProduct("Google.Protobuf")] +[assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] +[assembly: AllowPartiallyTrustedCallers] -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("2.4.1.555")] - -[assembly: AssemblyVersion("2.4.1.555")] - -#if !NOFILEVERSION -[assembly: AssemblyFileVersion("2.4.1.555")] +#if SIGNED +[assembly: InternalsVisibleTo("Google.Protobuf.Test, PublicKey=" + + "002400000480000094000000060200000024000052534131000400000100010025800fbcfc63a1" + + "7c66b303aae80b03a6beaa176bb6bef883be436f2a1579edd80ce23edf151a1f4ced97af83abcd" + + "981207041fd5b2da3b498346fcfcd94910d52f25537c4a43ce3fbe17dc7d43e6cbdb4d8f1242dc" + + "b6bd9b5906be74da8daa7d7280f97130f318a16c07baf118839b156299a48522f9fae2371c9665" + + "c5ae9cb6")] +#else +[assembly: InternalsVisibleTo("Google.Protobuf.Test")] #endif +[assembly: AssemblyVersion("3.0.0.0")] +[assembly: AssemblyFileVersion("3.0.0.0")] +[assembly: AssemblyInformationalVersion("3.0.0-alpha4")] diff --git a/csharp/src/ProtocolBuffers/Descriptors/IndexedDescriptorBase.cs b/csharp/src/Google.Protobuf/Reflection/DescriptorBase.cs similarity index 67% rename from csharp/src/ProtocolBuffers/Descriptors/IndexedDescriptorBase.cs rename to csharp/src/Google.Protobuf/Reflection/DescriptorBase.cs index bdb4eb82cde6f..194041a88942c 100644 --- a/csharp/src/ProtocolBuffers/Descriptors/IndexedDescriptorBase.cs +++ b/csharp/src/Google.Protobuf/Reflection/DescriptorBase.cs @@ -1,64 +1,85 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -using Google.ProtocolBuffers.DescriptorProtos; - -namespace Google.ProtocolBuffers.Descriptors -{ - /// - /// Base class for descriptors which are also indexed. This is all of them other than - /// . - /// - public abstract class IndexedDescriptorBase : DescriptorBase - where TProto : IMessage, IDescriptorProto - { - private readonly int index; - - protected IndexedDescriptorBase(TProto proto, FileDescriptor file, string fullName, int index) - : base(proto, file, fullName) - { - this.index = index; - } - - /// - /// The index of this descriptor within its parent descriptor. - /// - /// - /// This returns the index of this descriptor within its parent, for - /// this descriptor's type. (There can be duplicate values for different - /// types, e.g. one enum type with index 0 and one message type with index 0.) - /// - public int Index - { - get { return index; } - } - } +#region Copyright notice and license +// 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. +#endregion + +namespace Google.Protobuf.Reflection +{ + /// + /// Base class for nearly all descriptors, providing common functionality. + /// + public abstract class DescriptorBase : IDescriptor + { + private readonly FileDescriptor file; + private readonly string fullName; + private readonly int index; + + internal DescriptorBase(FileDescriptor file, string fullName, int index) + { + this.file = file; + this.fullName = fullName; + this.index = index; + } + + /// + /// The index of this descriptor within its parent descriptor. + /// + /// + /// This returns the index of this descriptor within its parent, for + /// this descriptor's type. (There can be duplicate values for different + /// types, e.g. one enum type with index 0 and one message type with index 0.) + /// + public int Index + { + get { return index; } + } + + /// + /// Returns the name of the entity (field, message etc) being described. + /// + public abstract string Name { get; } + + /// + /// The fully qualified name of the descriptor's target. + /// + public string FullName + { + get { return fullName; } + } + + /// + /// The file this descriptor was declared in. + /// + public FileDescriptor File + { + get { return file; } + } + } } \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers/Descriptors/DescriptorPool.cs b/csharp/src/Google.Protobuf/Reflection/DescriptorPool.cs similarity index 94% rename from csharp/src/ProtocolBuffers/Descriptors/DescriptorPool.cs rename to csharp/src/Google.Protobuf/Reflection/DescriptorPool.cs index 30718709e9d75..759955e635f86 100644 --- a/csharp/src/ProtocolBuffers/Descriptors/DescriptorPool.cs +++ b/csharp/src/Google.Protobuf/Reflection/DescriptorPool.cs @@ -1,364 +1,366 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -using System; -using System.Collections.Generic; -using System.Text; -using System.Text.RegularExpressions; - -namespace Google.ProtocolBuffers.Descriptors -{ - /// - /// Contains lookup tables containing all the descriptors defined in a particular file. - /// - internal sealed class DescriptorPool - { - private readonly IDictionary descriptorsByName = - new Dictionary(); - - private readonly IDictionary fieldsByNumber = - new Dictionary(); - - private readonly IDictionary enumValuesByNumber = - new Dictionary(); - - private readonly HashSet dependencies; - - internal DescriptorPool(FileDescriptor[] dependencyFiles) - { - dependencies = new HashSet(); - for (int i = 0; i < dependencyFiles.Length; i++) - { - dependencies.Add(dependencyFiles[i]); - ImportPublicDependencies(dependencyFiles[i]); - } - - foreach (FileDescriptor dependency in dependencyFiles) - { - AddPackage(dependency.Package, dependency); - } - } - - private void ImportPublicDependencies(FileDescriptor file) - { - foreach (FileDescriptor dependency in file.PublicDependencies) - { - if (dependencies.Add(dependency)) - { - ImportPublicDependencies(dependency); - } - } - } - - /// - /// Finds a symbol of the given name within the pool. - /// - /// The type of symbol to look for - /// Fully-qualified name to look up - /// The symbol with the given name and type, - /// or null if the symbol doesn't exist or has the wrong type - internal T FindSymbol(string fullName) where T : class, IDescriptor - { - IDescriptor result; - descriptorsByName.TryGetValue(fullName, out result); - T descriptor = result as T; - if (descriptor != null) - { - return descriptor; - } - - foreach (FileDescriptor dependency in dependencies) - { - dependency.DescriptorPool.descriptorsByName.TryGetValue(fullName, out result); - descriptor = result as T; - if (descriptor != null) - { - return descriptor; - } - } - - return null; - } - - /// - /// Adds a package to the symbol tables. If a package by the same name - /// already exists, that is fine, but if some other kind of symbol - /// exists under the same name, an exception is thrown. If the package - /// has multiple components, this also adds the parent package(s). - /// - internal void AddPackage(string fullName, FileDescriptor file) - { - int dotpos = fullName.LastIndexOf('.'); - String name; - if (dotpos != -1) - { - AddPackage(fullName.Substring(0, dotpos), file); - name = fullName.Substring(dotpos + 1); - } - else - { - name = fullName; - } - - IDescriptor old; - if (descriptorsByName.TryGetValue(fullName, out old)) - { - if (!(old is PackageDescriptor)) - { - throw new DescriptorValidationException(file, - "\"" + name + - "\" is already defined (as something other than a " + - "package) in file \"" + old.File.Name + "\"."); - } - } - descriptorsByName[fullName] = new PackageDescriptor(name, fullName, file); - } - - /// - /// Adds a symbol to the symbol table. - /// - /// The symbol already existed - /// in the symbol table. - internal void AddSymbol(IDescriptor descriptor) - { - ValidateSymbolName(descriptor); - String fullName = descriptor.FullName; - - IDescriptor old; - if (descriptorsByName.TryGetValue(fullName, out old)) - { - int dotPos = fullName.LastIndexOf('.'); - string message; - if (descriptor.File == old.File) - { - if (dotPos == -1) - { - message = "\"" + fullName + "\" is already defined."; - } - else - { - message = "\"" + fullName.Substring(dotPos + 1) + "\" is already defined in \"" + - fullName.Substring(0, dotPos) + "\"."; - } - } - else - { - message = "\"" + fullName + "\" is already defined in file \"" + old.File.Name + "\"."; - } - throw new DescriptorValidationException(descriptor, message); - } - descriptorsByName[fullName] = descriptor; - } - - private static readonly Regex ValidationRegex = new Regex("^[_A-Za-z][_A-Za-z0-9]*$", - FrameworkPortability.CompiledRegexWhereAvailable); - - /// - /// Verifies that the descriptor's name is valid (i.e. it contains - /// only letters, digits and underscores, and does not start with a digit). - /// - /// - private static void ValidateSymbolName(IDescriptor descriptor) - { - if (descriptor.Name == "") - { - throw new DescriptorValidationException(descriptor, "Missing name."); - } - if (!ValidationRegex.IsMatch(descriptor.Name)) - { - throw new DescriptorValidationException(descriptor, - "\"" + descriptor.Name + "\" is not a valid identifier."); - } - } - - /// - /// Returns the field with the given number in the given descriptor, - /// or null if it can't be found. - /// - internal FieldDescriptor FindFieldByNumber(MessageDescriptor messageDescriptor, int number) - { - FieldDescriptor ret; - fieldsByNumber.TryGetValue(new DescriptorIntPair(messageDescriptor, number), out ret); - return ret; - } - - internal EnumValueDescriptor FindEnumValueByNumber(EnumDescriptor enumDescriptor, int number) - { - EnumValueDescriptor ret; - enumValuesByNumber.TryGetValue(new DescriptorIntPair(enumDescriptor, number), out ret); - return ret; - } - - /// - /// Adds a field to the fieldsByNumber table. - /// - /// A field with the same - /// containing type and number already exists. - internal void AddFieldByNumber(FieldDescriptor field) - { - DescriptorIntPair key = new DescriptorIntPair(field.ContainingType, field.FieldNumber); - FieldDescriptor old; - if (fieldsByNumber.TryGetValue(key, out old)) - { - throw new DescriptorValidationException(field, "Field number " + field.FieldNumber + - "has already been used in \"" + - field.ContainingType.FullName + - "\" by field \"" + old.Name + "\"."); - } - fieldsByNumber[key] = field; - } - - /// - /// Adds an enum value to the enumValuesByNumber table. If an enum value - /// with the same type and number already exists, this method does nothing. - /// (This is allowed; the first value defined with the number takes precedence.) - /// - internal void AddEnumValueByNumber(EnumValueDescriptor enumValue) - { - DescriptorIntPair key = new DescriptorIntPair(enumValue.EnumDescriptor, enumValue.Number); - if (!enumValuesByNumber.ContainsKey(key)) - { - enumValuesByNumber[key] = enumValue; - } - } - - /// - /// Looks up a descriptor by name, relative to some other descriptor. - /// The name may be fully-qualified (with a leading '.'), partially-qualified, - /// or unqualified. C++-like name lookup semantics are used to search for the - /// matching descriptor. - /// - public IDescriptor LookupSymbol(string name, IDescriptor relativeTo) - { - // TODO(jonskeet): This could be optimized in a number of ways. - - IDescriptor result; - if (name.StartsWith(".")) - { - // Fully-qualified name. - result = FindSymbol(name.Substring(1)); - } - else - { - // If "name" is a compound identifier, we want to search for the - // first component of it, then search within it for the rest. - int firstPartLength = name.IndexOf('.'); - string firstPart = firstPartLength == -1 ? name : name.Substring(0, firstPartLength); - - // We will search each parent scope of "relativeTo" looking for the - // symbol. - StringBuilder scopeToTry = new StringBuilder(relativeTo.FullName); - - while (true) - { - // Chop off the last component of the scope. - - // TODO(jonskeet): Make this more efficient. May not be worth using StringBuilder at all - int dotpos = scopeToTry.ToString().LastIndexOf("."); - if (dotpos == -1) - { - result = FindSymbol(name); - break; - } - else - { - scopeToTry.Length = dotpos + 1; - - // Append firstPart and try to find. - scopeToTry.Append(firstPart); - result = FindSymbol(scopeToTry.ToString()); - - if (result != null) - { - if (firstPartLength != -1) - { - // We only found the first part of the symbol. Now look for - // the whole thing. If this fails, we *don't* want to keep - // searching parent scopes. - scopeToTry.Length = dotpos + 1; - scopeToTry.Append(name); - result = FindSymbol(scopeToTry.ToString()); - } - break; - } - - // Not found. Remove the name so we can try again. - scopeToTry.Length = dotpos; - } - } - } - - if (result == null) - { - throw new DescriptorValidationException(relativeTo, "\"" + name + "\" is not defined."); - } - else - { - return result; - } - } - - /// - /// Struct used to hold the keys for the fieldByNumber table. - /// - private struct DescriptorIntPair : IEquatable - { - private readonly int number; - private readonly IDescriptor descriptor; - - internal DescriptorIntPair(IDescriptor descriptor, int number) - { - this.number = number; - this.descriptor = descriptor; - } - - public bool Equals(DescriptorIntPair other) - { - return descriptor == other.descriptor - && number == other.number; - } - - public override bool Equals(object obj) - { - if (obj is DescriptorIntPair) - { - return Equals((DescriptorIntPair) obj); - } - return false; - } - - public override int GetHashCode() - { - return descriptor.GetHashCode()*((1 << 16) - 1) + number; - } - } - } +#region Copyright notice and license +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Text; +using System.Text.RegularExpressions; + +namespace Google.Protobuf.Reflection +{ + /// + /// Contains lookup tables containing all the descriptors defined in a particular file. + /// + internal sealed class DescriptorPool + { + private readonly IDictionary descriptorsByName = + new Dictionary(); + + private readonly IDictionary fieldsByNumber = + new Dictionary(); + + private readonly IDictionary enumValuesByNumber = + new Dictionary(); + + private readonly HashSet dependencies; + + internal DescriptorPool(FileDescriptor[] dependencyFiles) + { + dependencies = new HashSet(); + for (int i = 0; i < dependencyFiles.Length; i++) + { + dependencies.Add(dependencyFiles[i]); + ImportPublicDependencies(dependencyFiles[i]); + } + + foreach (FileDescriptor dependency in dependencyFiles) + { + AddPackage(dependency.Package, dependency); + } + } + + private void ImportPublicDependencies(FileDescriptor file) + { + foreach (FileDescriptor dependency in file.PublicDependencies) + { + if (dependencies.Add(dependency)) + { + ImportPublicDependencies(dependency); + } + } + } + + /// + /// Finds a symbol of the given name within the pool. + /// + /// The type of symbol to look for + /// Fully-qualified name to look up + /// The symbol with the given name and type, + /// or null if the symbol doesn't exist or has the wrong type + internal T FindSymbol(string fullName) where T : class + { + IDescriptor result; + descriptorsByName.TryGetValue(fullName, out result); + T descriptor = result as T; + if (descriptor != null) + { + return descriptor; + } + + foreach (FileDescriptor dependency in dependencies) + { + dependency.DescriptorPool.descriptorsByName.TryGetValue(fullName, out result); + descriptor = result as T; + if (descriptor != null) + { + return descriptor; + } + } + + return null; + } + + /// + /// Adds a package to the symbol tables. If a package by the same name + /// already exists, that is fine, but if some other kind of symbol + /// exists under the same name, an exception is thrown. If the package + /// has multiple components, this also adds the parent package(s). + /// + internal void AddPackage(string fullName, FileDescriptor file) + { + int dotpos = fullName.LastIndexOf('.'); + String name; + if (dotpos != -1) + { + AddPackage(fullName.Substring(0, dotpos), file); + name = fullName.Substring(dotpos + 1); + } + else + { + name = fullName; + } + + IDescriptor old; + if (descriptorsByName.TryGetValue(fullName, out old)) + { + if (!(old is PackageDescriptor)) + { + throw new DescriptorValidationException(file, + "\"" + name + + "\" is already defined (as something other than a " + + "package) in file \"" + old.File.Name + "\"."); + } + } + descriptorsByName[fullName] = new PackageDescriptor(name, fullName, file); + } + + /// + /// Adds a symbol to the symbol table. + /// + /// The symbol already existed + /// in the symbol table. + internal void AddSymbol(IDescriptor descriptor) + { + ValidateSymbolName(descriptor); + String fullName = descriptor.FullName; + + IDescriptor old; + if (descriptorsByName.TryGetValue(fullName, out old)) + { + int dotPos = fullName.LastIndexOf('.'); + string message; + if (descriptor.File == old.File) + { + if (dotPos == -1) + { + message = "\"" + fullName + "\" is already defined."; + } + else + { + message = "\"" + fullName.Substring(dotPos + 1) + "\" is already defined in \"" + + fullName.Substring(0, dotPos) + "\"."; + } + } + else + { + message = "\"" + fullName + "\" is already defined in file \"" + old.File.Name + "\"."; + } + throw new DescriptorValidationException(descriptor, message); + } + descriptorsByName[fullName] = descriptor; + } + + private static readonly Regex ValidationRegex = new Regex("^[_A-Za-z][_A-Za-z0-9]*$", + FrameworkPortability.CompiledRegexWhereAvailable); + + /// + /// Verifies that the descriptor's name is valid (i.e. it contains + /// only letters, digits and underscores, and does not start with a digit). + /// + /// + private static void ValidateSymbolName(IDescriptor descriptor) + { + if (descriptor.Name == "") + { + throw new DescriptorValidationException(descriptor, "Missing name."); + } + if (!ValidationRegex.IsMatch(descriptor.Name)) + { + throw new DescriptorValidationException(descriptor, + "\"" + descriptor.Name + "\" is not a valid identifier."); + } + } + + /// + /// Returns the field with the given number in the given descriptor, + /// or null if it can't be found. + /// + internal FieldDescriptor FindFieldByNumber(MessageDescriptor messageDescriptor, int number) + { + FieldDescriptor ret; + fieldsByNumber.TryGetValue(new DescriptorIntPair(messageDescriptor, number), out ret); + return ret; + } + + internal EnumValueDescriptor FindEnumValueByNumber(EnumDescriptor enumDescriptor, int number) + { + EnumValueDescriptor ret; + enumValuesByNumber.TryGetValue(new DescriptorIntPair(enumDescriptor, number), out ret); + return ret; + } + + /// + /// Adds a field to the fieldsByNumber table. + /// + /// A field with the same + /// containing type and number already exists. + internal void AddFieldByNumber(FieldDescriptor field) + { + DescriptorIntPair key = new DescriptorIntPair(field.ContainingType, field.FieldNumber); + FieldDescriptor old; + if (fieldsByNumber.TryGetValue(key, out old)) + { + throw new DescriptorValidationException(field, "Field number " + field.FieldNumber + + "has already been used in \"" + + field.ContainingType.FullName + + "\" by field \"" + old.Name + "\"."); + } + fieldsByNumber[key] = field; + } + + /// + /// Adds an enum value to the enumValuesByNumber table. If an enum value + /// with the same type and number already exists, this method does nothing. + /// (This is allowed; the first value defined with the number takes precedence.) + /// + internal void AddEnumValueByNumber(EnumValueDescriptor enumValue) + { + DescriptorIntPair key = new DescriptorIntPair(enumValue.EnumDescriptor, enumValue.Number); + if (!enumValuesByNumber.ContainsKey(key)) + { + enumValuesByNumber[key] = enumValue; + } + } + + /// + /// Looks up a descriptor by name, relative to some other descriptor. + /// The name may be fully-qualified (with a leading '.'), partially-qualified, + /// or unqualified. C++-like name lookup semantics are used to search for the + /// matching descriptor. + /// + /// + /// This isn't heavily optimized, but it's only used during cross linking anyway. + /// If it starts being used more widely, we should look at performance more carefully. + /// + internal IDescriptor LookupSymbol(string name, IDescriptor relativeTo) + { + IDescriptor result; + if (name.StartsWith(".")) + { + // Fully-qualified name. + result = FindSymbol(name.Substring(1)); + } + else + { + // If "name" is a compound identifier, we want to search for the + // first component of it, then search within it for the rest. + int firstPartLength = name.IndexOf('.'); + string firstPart = firstPartLength == -1 ? name : name.Substring(0, firstPartLength); + + // We will search each parent scope of "relativeTo" looking for the + // symbol. + StringBuilder scopeToTry = new StringBuilder(relativeTo.FullName); + + while (true) + { + // Chop off the last component of the scope. + + int dotpos = scopeToTry.ToString().LastIndexOf("."); + if (dotpos == -1) + { + result = FindSymbol(name); + break; + } + else + { + scopeToTry.Length = dotpos + 1; + + // Append firstPart and try to find. + scopeToTry.Append(firstPart); + result = FindSymbol(scopeToTry.ToString()); + + if (result != null) + { + if (firstPartLength != -1) + { + // We only found the first part of the symbol. Now look for + // the whole thing. If this fails, we *don't* want to keep + // searching parent scopes. + scopeToTry.Length = dotpos + 1; + scopeToTry.Append(name); + result = FindSymbol(scopeToTry.ToString()); + } + break; + } + + // Not found. Remove the name so we can try again. + scopeToTry.Length = dotpos; + } + } + } + + if (result == null) + { + throw new DescriptorValidationException(relativeTo, "\"" + name + "\" is not defined."); + } + else + { + return result; + } + } + + /// + /// Struct used to hold the keys for the fieldByNumber table. + /// + private struct DescriptorIntPair : IEquatable + { + private readonly int number; + private readonly IDescriptor descriptor; + + internal DescriptorIntPair(IDescriptor descriptor, int number) + { + this.number = number; + this.descriptor = descriptor; + } + + public bool Equals(DescriptorIntPair other) + { + return descriptor == other.descriptor + && number == other.number; + } + + public override bool Equals(object obj) + { + if (obj is DescriptorIntPair) + { + return Equals((DescriptorIntPair) obj); + } + return false; + } + + public override int GetHashCode() + { + return descriptor.GetHashCode()*((1 << 16) - 1) + number; + } + } + } } \ No newline at end of file diff --git a/csharp/src/Google.Protobuf/Reflection/DescriptorProtoFile.cs b/csharp/src/Google.Protobuf/Reflection/DescriptorProtoFile.cs new file mode 100644 index 0000000000000..39cb38f481cf3 --- /dev/null +++ b/csharp/src/Google.Protobuf/Reflection/DescriptorProtoFile.cs @@ -0,0 +1,4437 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/descriptor_proto_file.proto +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace Google.Protobuf.Reflection { + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + internal static partial class DescriptorProtoFile { + + #region Descriptor + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static DescriptorProtoFile() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "Citnb29nbGUvcHJvdG9idWYvZGVzY3JpcHRvcl9wcm90b19maWxlLnByb3Rv", + "Eg9nb29nbGUucHJvdG9idWYiRwoRRmlsZURlc2NyaXB0b3JTZXQSMgoEZmls", + "ZRgBIAMoCzIkLmdvb2dsZS5wcm90b2J1Zi5GaWxlRGVzY3JpcHRvclByb3Rv", + "ItsDChNGaWxlRGVzY3JpcHRvclByb3RvEgwKBG5hbWUYASABKAkSDwoHcGFj", + "a2FnZRgCIAEoCRISCgpkZXBlbmRlbmN5GAMgAygJEhkKEXB1YmxpY19kZXBl", + "bmRlbmN5GAogAygFEhcKD3dlYWtfZGVwZW5kZW5jeRgLIAMoBRI2CgxtZXNz", + "YWdlX3R5cGUYBCADKAsyIC5nb29nbGUucHJvdG9idWYuRGVzY3JpcHRvclBy", + "b3RvEjcKCWVudW1fdHlwZRgFIAMoCzIkLmdvb2dsZS5wcm90b2J1Zi5FbnVt", + "RGVzY3JpcHRvclByb3RvEjgKB3NlcnZpY2UYBiADKAsyJy5nb29nbGUucHJv", + "dG9idWYuU2VydmljZURlc2NyaXB0b3JQcm90bxI4CglleHRlbnNpb24YByAD", + "KAsyJS5nb29nbGUucHJvdG9idWYuRmllbGREZXNjcmlwdG9yUHJvdG8SLQoH", + "b3B0aW9ucxgIIAEoCzIcLmdvb2dsZS5wcm90b2J1Zi5GaWxlT3B0aW9ucxI5", + "ChBzb3VyY2VfY29kZV9pbmZvGAkgASgLMh8uZ29vZ2xlLnByb3RvYnVmLlNv", + "dXJjZUNvZGVJbmZvEg4KBnN5bnRheBgMIAEoCSLwBAoPRGVzY3JpcHRvclBy", + "b3RvEgwKBG5hbWUYASABKAkSNAoFZmllbGQYAiADKAsyJS5nb29nbGUucHJv", + "dG9idWYuRmllbGREZXNjcmlwdG9yUHJvdG8SOAoJZXh0ZW5zaW9uGAYgAygL", + "MiUuZ29vZ2xlLnByb3RvYnVmLkZpZWxkRGVzY3JpcHRvclByb3RvEjUKC25l", + "c3RlZF90eXBlGAMgAygLMiAuZ29vZ2xlLnByb3RvYnVmLkRlc2NyaXB0b3JQ", + "cm90bxI3CgllbnVtX3R5cGUYBCADKAsyJC5nb29nbGUucHJvdG9idWYuRW51", + "bURlc2NyaXB0b3JQcm90bxJICg9leHRlbnNpb25fcmFuZ2UYBSADKAsyLy5n", + "b29nbGUucHJvdG9idWYuRGVzY3JpcHRvclByb3RvLkV4dGVuc2lvblJhbmdl", + "EjkKCm9uZW9mX2RlY2wYCCADKAsyJS5nb29nbGUucHJvdG9idWYuT25lb2ZE", + "ZXNjcmlwdG9yUHJvdG8SMAoHb3B0aW9ucxgHIAEoCzIfLmdvb2dsZS5wcm90", + "b2J1Zi5NZXNzYWdlT3B0aW9ucxJGCg5yZXNlcnZlZF9yYW5nZRgJIAMoCzIu", + "Lmdvb2dsZS5wcm90b2J1Zi5EZXNjcmlwdG9yUHJvdG8uUmVzZXJ2ZWRSYW5n", + "ZRIVCg1yZXNlcnZlZF9uYW1lGAogAygJGiwKDkV4dGVuc2lvblJhbmdlEg0K", + "BXN0YXJ0GAEgASgFEgsKA2VuZBgCIAEoBRorCg1SZXNlcnZlZFJhbmdlEg0K", + "BXN0YXJ0GAEgASgFEgsKA2VuZBgCIAEoBSKpBQoURmllbGREZXNjcmlwdG9y", + "UHJvdG8SDAoEbmFtZRgBIAEoCRIOCgZudW1iZXIYAyABKAUSOgoFbGFiZWwY", + "BCABKA4yKy5nb29nbGUucHJvdG9idWYuRmllbGREZXNjcmlwdG9yUHJvdG8u", + "TGFiZWwSOAoEdHlwZRgFIAEoDjIqLmdvb2dsZS5wcm90b2J1Zi5GaWVsZERl", + "c2NyaXB0b3JQcm90by5UeXBlEhEKCXR5cGVfbmFtZRgGIAEoCRIQCghleHRl", + "bmRlZRgCIAEoCRIVCg1kZWZhdWx0X3ZhbHVlGAcgASgJEhMKC29uZW9mX2lu", + "ZGV4GAkgASgFEi4KB29wdGlvbnMYCCABKAsyHS5nb29nbGUucHJvdG9idWYu", + "RmllbGRPcHRpb25zIrYCCgRUeXBlEg8KC1RZUEVfRE9VQkxFEAESDgoKVFlQ", + "RV9GTE9BVBACEg4KClRZUEVfSU5UNjQQAxIPCgtUWVBFX1VJTlQ2NBAEEg4K", + "ClRZUEVfSU5UMzIQBRIQCgxUWVBFX0ZJWEVENjQQBhIQCgxUWVBFX0ZJWEVE", + "MzIQBxINCglUWVBFX0JPT0wQCBIPCgtUWVBFX1NUUklORxAJEg4KClRZUEVf", + "R1JPVVAQChIQCgxUWVBFX01FU1NBR0UQCxIOCgpUWVBFX0JZVEVTEAwSDwoL", + "VFlQRV9VSU5UMzIQDRINCglUWVBFX0VOVU0QDhIRCg1UWVBFX1NGSVhFRDMy", + "EA8SEQoNVFlQRV9TRklYRUQ2NBAQEg8KC1RZUEVfU0lOVDMyEBESDwoLVFlQ", + "RV9TSU5UNjQQEiJDCgVMYWJlbBISCg5MQUJFTF9PUFRJT05BTBABEhIKDkxB", + "QkVMX1JFUVVJUkVEEAISEgoOTEFCRUxfUkVQRUFURUQQAyIkChRPbmVvZkRl", + "c2NyaXB0b3JQcm90bxIMCgRuYW1lGAEgASgJIowBChNFbnVtRGVzY3JpcHRv", + "clByb3RvEgwKBG5hbWUYASABKAkSOAoFdmFsdWUYAiADKAsyKS5nb29nbGUu", + "cHJvdG9idWYuRW51bVZhbHVlRGVzY3JpcHRvclByb3RvEi0KB29wdGlvbnMY", + "AyABKAsyHC5nb29nbGUucHJvdG9idWYuRW51bU9wdGlvbnMibAoYRW51bVZh", + "bHVlRGVzY3JpcHRvclByb3RvEgwKBG5hbWUYASABKAkSDgoGbnVtYmVyGAIg", + "ASgFEjIKB29wdGlvbnMYAyABKAsyIS5nb29nbGUucHJvdG9idWYuRW51bVZh", + "bHVlT3B0aW9ucyKQAQoWU2VydmljZURlc2NyaXB0b3JQcm90bxIMCgRuYW1l", + "GAEgASgJEjYKBm1ldGhvZBgCIAMoCzImLmdvb2dsZS5wcm90b2J1Zi5NZXRo", + "b2REZXNjcmlwdG9yUHJvdG8SMAoHb3B0aW9ucxgDIAEoCzIfLmdvb2dsZS5w", + "cm90b2J1Zi5TZXJ2aWNlT3B0aW9ucyLBAQoVTWV0aG9kRGVzY3JpcHRvclBy", + "b3RvEgwKBG5hbWUYASABKAkSEgoKaW5wdXRfdHlwZRgCIAEoCRITCgtvdXRw", + "dXRfdHlwZRgDIAEoCRIvCgdvcHRpb25zGAQgASgLMh4uZ29vZ2xlLnByb3Rv", + "YnVmLk1ldGhvZE9wdGlvbnMSHwoQY2xpZW50X3N0cmVhbWluZxgFIAEoCDoF", + "ZmFsc2USHwoQc2VydmVyX3N0cmVhbWluZxgGIAEoCDoFZmFsc2UiqgUKC0Zp", + "bGVPcHRpb25zEhQKDGphdmFfcGFja2FnZRgBIAEoCRIcChRqYXZhX291dGVy", + "X2NsYXNzbmFtZRgIIAEoCRIiChNqYXZhX211bHRpcGxlX2ZpbGVzGAogASgI", + "OgVmYWxzZRIsCh1qYXZhX2dlbmVyYXRlX2VxdWFsc19hbmRfaGFzaBgUIAEo", + "CDoFZmFsc2USJQoWamF2YV9zdHJpbmdfY2hlY2tfdXRmOBgbIAEoCDoFZmFs", + "c2USRgoMb3B0aW1pemVfZm9yGAkgASgOMikuZ29vZ2xlLnByb3RvYnVmLkZp", + "bGVPcHRpb25zLk9wdGltaXplTW9kZToFU1BFRUQSEgoKZ29fcGFja2FnZRgL", + "IAEoCRIiChNjY19nZW5lcmljX3NlcnZpY2VzGBAgASgIOgVmYWxzZRIkChVq", + "YXZhX2dlbmVyaWNfc2VydmljZXMYESABKAg6BWZhbHNlEiIKE3B5X2dlbmVy", + "aWNfc2VydmljZXMYEiABKAg6BWZhbHNlEhkKCmRlcHJlY2F0ZWQYFyABKAg6", + "BWZhbHNlEh8KEGNjX2VuYWJsZV9hcmVuYXMYHyABKAg6BWZhbHNlEhkKEW9i", + "amNfY2xhc3NfcHJlZml4GCQgASgJEhgKEGNzaGFycF9uYW1lc3BhY2UYJSAB", + "KAkSJwofamF2YW5hbm9fdXNlX2RlcHJlY2F0ZWRfcGFja2FnZRgmIAEoCBJD", + "ChR1bmludGVycHJldGVkX29wdGlvbhjnByADKAsyJC5nb29nbGUucHJvdG9i", + "dWYuVW5pbnRlcnByZXRlZE9wdGlvbiI6CgxPcHRpbWl6ZU1vZGUSCQoFU1BF", + "RUQQARINCglDT0RFX1NJWkUQAhIQCgxMSVRFX1JVTlRJTUUQAyoJCOgHEICA", + "gIACIuYBCg5NZXNzYWdlT3B0aW9ucxImChdtZXNzYWdlX3NldF93aXJlX2Zv", + "cm1hdBgBIAEoCDoFZmFsc2USLgofbm9fc3RhbmRhcmRfZGVzY3JpcHRvcl9h", + "Y2Nlc3NvchgCIAEoCDoFZmFsc2USGQoKZGVwcmVjYXRlZBgDIAEoCDoFZmFs", + "c2USEQoJbWFwX2VudHJ5GAcgASgIEkMKFHVuaW50ZXJwcmV0ZWRfb3B0aW9u", + "GOcHIAMoCzIkLmdvb2dsZS5wcm90b2J1Zi5VbmludGVycHJldGVkT3B0aW9u", + "KgkI6AcQgICAgAIimAMKDEZpZWxkT3B0aW9ucxI6CgVjdHlwZRgBIAEoDjIj", + "Lmdvb2dsZS5wcm90b2J1Zi5GaWVsZE9wdGlvbnMuQ1R5cGU6BlNUUklORxIO", + "CgZwYWNrZWQYAiABKAgSPwoGanN0eXBlGAYgASgOMiQuZ29vZ2xlLnByb3Rv", + "YnVmLkZpZWxkT3B0aW9ucy5KU1R5cGU6CUpTX05PUk1BTBITCgRsYXp5GAUg", + "ASgIOgVmYWxzZRIZCgpkZXByZWNhdGVkGAMgASgIOgVmYWxzZRITCgR3ZWFr", + "GAogASgIOgVmYWxzZRJDChR1bmludGVycHJldGVkX29wdGlvbhjnByADKAsy", + "JC5nb29nbGUucHJvdG9idWYuVW5pbnRlcnByZXRlZE9wdGlvbiIvCgVDVHlw", + "ZRIKCgZTVFJJTkcQABIICgRDT1JEEAESEAoMU1RSSU5HX1BJRUNFEAIiNQoG", + "SlNUeXBlEg0KCUpTX05PUk1BTBAAEg0KCUpTX1NUUklORxABEg0KCUpTX05V", + "TUJFUhACKgkI6AcQgICAgAIijQEKC0VudW1PcHRpb25zEhMKC2FsbG93X2Fs", + "aWFzGAIgASgIEhkKCmRlcHJlY2F0ZWQYAyABKAg6BWZhbHNlEkMKFHVuaW50", + "ZXJwcmV0ZWRfb3B0aW9uGOcHIAMoCzIkLmdvb2dsZS5wcm90b2J1Zi5Vbmlu", + "dGVycHJldGVkT3B0aW9uKgkI6AcQgICAgAIifQoQRW51bVZhbHVlT3B0aW9u", + "cxIZCgpkZXByZWNhdGVkGAEgASgIOgVmYWxzZRJDChR1bmludGVycHJldGVk", + "X29wdGlvbhjnByADKAsyJC5nb29nbGUucHJvdG9idWYuVW5pbnRlcnByZXRl", + "ZE9wdGlvbioJCOgHEICAgIACInsKDlNlcnZpY2VPcHRpb25zEhkKCmRlcHJl", + "Y2F0ZWQYISABKAg6BWZhbHNlEkMKFHVuaW50ZXJwcmV0ZWRfb3B0aW9uGOcH", + "IAMoCzIkLmdvb2dsZS5wcm90b2J1Zi5VbmludGVycHJldGVkT3B0aW9uKgkI", + "6AcQgICAgAIiegoNTWV0aG9kT3B0aW9ucxIZCgpkZXByZWNhdGVkGCEgASgI", + "OgVmYWxzZRJDChR1bmludGVycHJldGVkX29wdGlvbhjnByADKAsyJC5nb29n", + "bGUucHJvdG9idWYuVW5pbnRlcnByZXRlZE9wdGlvbioJCOgHEICAgIACIp4C", + "ChNVbmludGVycHJldGVkT3B0aW9uEjsKBG5hbWUYAiADKAsyLS5nb29nbGUu", + "cHJvdG9idWYuVW5pbnRlcnByZXRlZE9wdGlvbi5OYW1lUGFydBIYChBpZGVu", + "dGlmaWVyX3ZhbHVlGAMgASgJEhoKEnBvc2l0aXZlX2ludF92YWx1ZRgEIAEo", + "BBIaChJuZWdhdGl2ZV9pbnRfdmFsdWUYBSABKAMSFAoMZG91YmxlX3ZhbHVl", + "GAYgASgBEhQKDHN0cmluZ192YWx1ZRgHIAEoDBIXCg9hZ2dyZWdhdGVfdmFs", + "dWUYCCABKAkaMwoITmFtZVBhcnQSEQoJbmFtZV9wYXJ0GAEgAigJEhQKDGlz", + "X2V4dGVuc2lvbhgCIAIoCCLVAQoOU291cmNlQ29kZUluZm8SOgoIbG9jYXRp", + "b24YASADKAsyKC5nb29nbGUucHJvdG9idWYuU291cmNlQ29kZUluZm8uTG9j", + "YXRpb24ahgEKCExvY2F0aW9uEhAKBHBhdGgYASADKAVCAhABEhAKBHNwYW4Y", + "AiADKAVCAhABEhgKEGxlYWRpbmdfY29tbWVudHMYAyABKAkSGQoRdHJhaWxp", + "bmdfY29tbWVudHMYBCABKAkSIQoZbGVhZGluZ19kZXRhY2hlZF9jb21tZW50", + "cxgGIAMoCUJbChNjb20uZ29vZ2xlLnByb3RvYnVmQhBEZXNjcmlwdG9yUHJv", + "dG9zSAFaCmRlc2NyaXB0b3KiAgNHUEKqAhpHb29nbGUuUHJvdG9idWYuUmVm", + "bGVjdGlvbrACAQ==")); + descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] { + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.Reflection.FileDescriptorSet), new[]{ "File" }, null, null, null), + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.Reflection.FileDescriptorProto), new[]{ "Name", "Package", "Dependency", "PublicDependency", "WeakDependency", "MessageType", "EnumType", "Service", "Extension", "Options", "SourceCodeInfo", "Syntax" }, null, null, null), + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.Reflection.DescriptorProto), new[]{ "Name", "Field", "Extension", "NestedType", "EnumType", "ExtensionRange", "OneofDecl", "Options", "ReservedRange", "ReservedName" }, null, null, new pbr::GeneratedCodeInfo[] { new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.Reflection.DescriptorProto.Types.ExtensionRange), new[]{ "Start", "End" }, null, null, null), + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.Reflection.DescriptorProto.Types.ReservedRange), new[]{ "Start", "End" }, null, null, null)}), + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.Reflection.FieldDescriptorProto), new[]{ "Name", "Number", "Label", "Type", "TypeName", "Extendee", "DefaultValue", "OneofIndex", "Options" }, null, new[]{ typeof(global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Type), typeof(global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Label) }, null), + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.Reflection.OneofDescriptorProto), new[]{ "Name" }, null, null, null), + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.Reflection.EnumDescriptorProto), new[]{ "Name", "Value", "Options" }, null, null, null), + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.Reflection.EnumValueDescriptorProto), new[]{ "Name", "Number", "Options" }, null, null, null), + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.Reflection.ServiceDescriptorProto), new[]{ "Name", "Method", "Options" }, null, null, null), + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.Reflection.MethodDescriptorProto), new[]{ "Name", "InputType", "OutputType", "Options", "ClientStreaming", "ServerStreaming" }, null, null, null), + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.Reflection.FileOptions), new[]{ "JavaPackage", "JavaOuterClassname", "JavaMultipleFiles", "JavaGenerateEqualsAndHash", "JavaStringCheckUtf8", "OptimizeFor", "GoPackage", "CcGenericServices", "JavaGenericServices", "PyGenericServices", "Deprecated", "CcEnableArenas", "ObjcClassPrefix", "CsharpNamespace", "JavananoUseDeprecatedPackage", "UninterpretedOption" }, null, new[]{ typeof(global::Google.Protobuf.Reflection.FileOptions.Types.OptimizeMode) }, null), + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.Reflection.MessageOptions), new[]{ "MessageSetWireFormat", "NoStandardDescriptorAccessor", "Deprecated", "MapEntry", "UninterpretedOption" }, null, null, null), + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.Reflection.FieldOptions), new[]{ "Ctype", "Packed", "Jstype", "Lazy", "Deprecated", "Weak", "UninterpretedOption" }, null, new[]{ typeof(global::Google.Protobuf.Reflection.FieldOptions.Types.CType), typeof(global::Google.Protobuf.Reflection.FieldOptions.Types.JSType) }, null), + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.Reflection.EnumOptions), new[]{ "AllowAlias", "Deprecated", "UninterpretedOption" }, null, null, null), + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.Reflection.EnumValueOptions), new[]{ "Deprecated", "UninterpretedOption" }, null, null, null), + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.Reflection.ServiceOptions), new[]{ "Deprecated", "UninterpretedOption" }, null, null, null), + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.Reflection.MethodOptions), new[]{ "Deprecated", "UninterpretedOption" }, null, null, null), + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.Reflection.UninterpretedOption), new[]{ "Name", "IdentifierValue", "PositiveIntValue", "NegativeIntValue", "DoubleValue", "StringValue", "AggregateValue" }, null, null, new pbr::GeneratedCodeInfo[] { new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.Reflection.UninterpretedOption.Types.NamePart), new[]{ "NamePart_", "IsExtension" }, null, null, null)}), + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.Reflection.SourceCodeInfo), new[]{ "Location" }, null, null, new pbr::GeneratedCodeInfo[] { new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.Reflection.SourceCodeInfo.Types.Location), new[]{ "Path", "Span", "LeadingComments", "TrailingComments", "LeadingDetachedComments" }, null, null, null)}) + })); + } + #endregion + + } + #region Messages + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + internal sealed partial class FileDescriptorSet : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new FileDescriptorSet()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorProtoFile.Descriptor.MessageTypes[0]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public FileDescriptorSet() { + OnConstruction(); + } + + partial void OnConstruction(); + + public FileDescriptorSet(FileDescriptorSet other) : this() { + file_ = other.file_.Clone(); + } + + public FileDescriptorSet Clone() { + return new FileDescriptorSet(this); + } + + public const int FileFieldNumber = 1; + private static readonly pb::FieldCodec _repeated_file_codec + = pb::FieldCodec.ForMessage(10, global::Google.Protobuf.Reflection.FileDescriptorProto.Parser); + private readonly pbc::RepeatedField file_ = new pbc::RepeatedField(); + public pbc::RepeatedField File { + get { return file_; } + } + + public override bool Equals(object other) { + return Equals(other as FileDescriptorSet); + } + + public bool Equals(FileDescriptorSet other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if(!file_.Equals(other.file_)) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + hash ^= file_.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + file_.WriteTo(output, _repeated_file_codec); + } + + public int CalculateSize() { + int size = 0; + size += file_.CalculateSize(_repeated_file_codec); + return size; + } + + public void MergeFrom(FileDescriptorSet other) { + if (other == null) { + return; + } + file_.Add(other.file_); + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 10: { + file_.AddEntriesFrom(input, _repeated_file_codec); + break; + } + } + } + } + + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + internal sealed partial class FileDescriptorProto : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new FileDescriptorProto()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorProtoFile.Descriptor.MessageTypes[1]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public FileDescriptorProto() { + OnConstruction(); + } + + partial void OnConstruction(); + + public FileDescriptorProto(FileDescriptorProto other) : this() { + name_ = other.name_; + package_ = other.package_; + dependency_ = other.dependency_.Clone(); + publicDependency_ = other.publicDependency_.Clone(); + weakDependency_ = other.weakDependency_.Clone(); + messageType_ = other.messageType_.Clone(); + enumType_ = other.enumType_.Clone(); + service_ = other.service_.Clone(); + extension_ = other.extension_.Clone(); + Options = other.options_ != null ? other.Options.Clone() : null; + SourceCodeInfo = other.sourceCodeInfo_ != null ? other.SourceCodeInfo.Clone() : null; + syntax_ = other.syntax_; + } + + public FileDescriptorProto Clone() { + return new FileDescriptorProto(this); + } + + public const int NameFieldNumber = 1; + private string name_ = ""; + public string Name { + get { return name_; } + set { + name_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int PackageFieldNumber = 2; + private string package_ = ""; + public string Package { + get { return package_; } + set { + package_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int DependencyFieldNumber = 3; + private static readonly pb::FieldCodec _repeated_dependency_codec + = pb::FieldCodec.ForString(26); + private readonly pbc::RepeatedField dependency_ = new pbc::RepeatedField(); + public pbc::RepeatedField Dependency { + get { return dependency_; } + } + + public const int PublicDependencyFieldNumber = 10; + private static readonly pb::FieldCodec _repeated_publicDependency_codec + = pb::FieldCodec.ForInt32(80); + private readonly pbc::RepeatedField publicDependency_ = new pbc::RepeatedField(); + public pbc::RepeatedField PublicDependency { + get { return publicDependency_; } + } + + public const int WeakDependencyFieldNumber = 11; + private static readonly pb::FieldCodec _repeated_weakDependency_codec + = pb::FieldCodec.ForInt32(88); + private readonly pbc::RepeatedField weakDependency_ = new pbc::RepeatedField(); + public pbc::RepeatedField WeakDependency { + get { return weakDependency_; } + } + + public const int MessageTypeFieldNumber = 4; + private static readonly pb::FieldCodec _repeated_messageType_codec + = pb::FieldCodec.ForMessage(34, global::Google.Protobuf.Reflection.DescriptorProto.Parser); + private readonly pbc::RepeatedField messageType_ = new pbc::RepeatedField(); + public pbc::RepeatedField MessageType { + get { return messageType_; } + } + + public const int EnumTypeFieldNumber = 5; + private static readonly pb::FieldCodec _repeated_enumType_codec + = pb::FieldCodec.ForMessage(42, global::Google.Protobuf.Reflection.EnumDescriptorProto.Parser); + private readonly pbc::RepeatedField enumType_ = new pbc::RepeatedField(); + public pbc::RepeatedField EnumType { + get { return enumType_; } + } + + public const int ServiceFieldNumber = 6; + private static readonly pb::FieldCodec _repeated_service_codec + = pb::FieldCodec.ForMessage(50, global::Google.Protobuf.Reflection.ServiceDescriptorProto.Parser); + private readonly pbc::RepeatedField service_ = new pbc::RepeatedField(); + public pbc::RepeatedField Service { + get { return service_; } + } + + public const int ExtensionFieldNumber = 7; + private static readonly pb::FieldCodec _repeated_extension_codec + = pb::FieldCodec.ForMessage(58, global::Google.Protobuf.Reflection.FieldDescriptorProto.Parser); + private readonly pbc::RepeatedField extension_ = new pbc::RepeatedField(); + public pbc::RepeatedField Extension { + get { return extension_; } + } + + public const int OptionsFieldNumber = 8; + private global::Google.Protobuf.Reflection.FileOptions options_; + public global::Google.Protobuf.Reflection.FileOptions Options { + get { return options_; } + set { + options_ = value; + } + } + + public const int SourceCodeInfoFieldNumber = 9; + private global::Google.Protobuf.Reflection.SourceCodeInfo sourceCodeInfo_; + public global::Google.Protobuf.Reflection.SourceCodeInfo SourceCodeInfo { + get { return sourceCodeInfo_; } + set { + sourceCodeInfo_ = value; + } + } + + public const int SyntaxFieldNumber = 12; + private string syntax_ = ""; + public string Syntax { + get { return syntax_; } + set { + syntax_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public override bool Equals(object other) { + return Equals(other as FileDescriptorProto); + } + + public bool Equals(FileDescriptorProto other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Name != other.Name) return false; + if (Package != other.Package) return false; + if(!dependency_.Equals(other.dependency_)) return false; + if(!publicDependency_.Equals(other.publicDependency_)) return false; + if(!weakDependency_.Equals(other.weakDependency_)) return false; + if(!messageType_.Equals(other.messageType_)) return false; + if(!enumType_.Equals(other.enumType_)) return false; + if(!service_.Equals(other.service_)) return false; + if(!extension_.Equals(other.extension_)) return false; + if (!object.Equals(Options, other.Options)) return false; + if (!object.Equals(SourceCodeInfo, other.SourceCodeInfo)) return false; + if (Syntax != other.Syntax) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (Name.Length != 0) hash ^= Name.GetHashCode(); + if (Package.Length != 0) hash ^= Package.GetHashCode(); + hash ^= dependency_.GetHashCode(); + hash ^= publicDependency_.GetHashCode(); + hash ^= weakDependency_.GetHashCode(); + hash ^= messageType_.GetHashCode(); + hash ^= enumType_.GetHashCode(); + hash ^= service_.GetHashCode(); + hash ^= extension_.GetHashCode(); + if (options_ != null) hash ^= Options.GetHashCode(); + if (sourceCodeInfo_ != null) hash ^= SourceCodeInfo.GetHashCode(); + if (Syntax.Length != 0) hash ^= Syntax.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (Name.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Name); + } + if (Package.Length != 0) { + output.WriteRawTag(18); + output.WriteString(Package); + } + dependency_.WriteTo(output, _repeated_dependency_codec); + messageType_.WriteTo(output, _repeated_messageType_codec); + enumType_.WriteTo(output, _repeated_enumType_codec); + service_.WriteTo(output, _repeated_service_codec); + extension_.WriteTo(output, _repeated_extension_codec); + if (options_ != null) { + output.WriteRawTag(66); + output.WriteMessage(Options); + } + if (sourceCodeInfo_ != null) { + output.WriteRawTag(74); + output.WriteMessage(SourceCodeInfo); + } + publicDependency_.WriteTo(output, _repeated_publicDependency_codec); + weakDependency_.WriteTo(output, _repeated_weakDependency_codec); + if (Syntax.Length != 0) { + output.WriteRawTag(98); + output.WriteString(Syntax); + } + } + + public int CalculateSize() { + int size = 0; + if (Name.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); + } + if (Package.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Package); + } + size += dependency_.CalculateSize(_repeated_dependency_codec); + size += publicDependency_.CalculateSize(_repeated_publicDependency_codec); + size += weakDependency_.CalculateSize(_repeated_weakDependency_codec); + size += messageType_.CalculateSize(_repeated_messageType_codec); + size += enumType_.CalculateSize(_repeated_enumType_codec); + size += service_.CalculateSize(_repeated_service_codec); + size += extension_.CalculateSize(_repeated_extension_codec); + if (options_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options); + } + if (sourceCodeInfo_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(SourceCodeInfo); + } + if (Syntax.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Syntax); + } + return size; + } + + public void MergeFrom(FileDescriptorProto other) { + if (other == null) { + return; + } + if (other.Name.Length != 0) { + Name = other.Name; + } + if (other.Package.Length != 0) { + Package = other.Package; + } + dependency_.Add(other.dependency_); + publicDependency_.Add(other.publicDependency_); + weakDependency_.Add(other.weakDependency_); + messageType_.Add(other.messageType_); + enumType_.Add(other.enumType_); + service_.Add(other.service_); + extension_.Add(other.extension_); + if (other.options_ != null) { + if (options_ == null) { + options_ = new global::Google.Protobuf.Reflection.FileOptions(); + } + Options.MergeFrom(other.Options); + } + if (other.sourceCodeInfo_ != null) { + if (sourceCodeInfo_ == null) { + sourceCodeInfo_ = new global::Google.Protobuf.Reflection.SourceCodeInfo(); + } + SourceCodeInfo.MergeFrom(other.SourceCodeInfo); + } + if (other.Syntax.Length != 0) { + Syntax = other.Syntax; + } + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 10: { + Name = input.ReadString(); + break; + } + case 18: { + Package = input.ReadString(); + break; + } + case 26: { + dependency_.AddEntriesFrom(input, _repeated_dependency_codec); + break; + } + case 34: { + messageType_.AddEntriesFrom(input, _repeated_messageType_codec); + break; + } + case 42: { + enumType_.AddEntriesFrom(input, _repeated_enumType_codec); + break; + } + case 50: { + service_.AddEntriesFrom(input, _repeated_service_codec); + break; + } + case 58: { + extension_.AddEntriesFrom(input, _repeated_extension_codec); + break; + } + case 66: { + if (options_ == null) { + options_ = new global::Google.Protobuf.Reflection.FileOptions(); + } + input.ReadMessage(options_); + break; + } + case 74: { + if (sourceCodeInfo_ == null) { + sourceCodeInfo_ = new global::Google.Protobuf.Reflection.SourceCodeInfo(); + } + input.ReadMessage(sourceCodeInfo_); + break; + } + case 82: + case 80: { + publicDependency_.AddEntriesFrom(input, _repeated_publicDependency_codec); + break; + } + case 90: + case 88: { + weakDependency_.AddEntriesFrom(input, _repeated_weakDependency_codec); + break; + } + case 98: { + Syntax = input.ReadString(); + break; + } + } + } + } + + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + internal sealed partial class DescriptorProto : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new DescriptorProto()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorProtoFile.Descriptor.MessageTypes[2]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public DescriptorProto() { + OnConstruction(); + } + + partial void OnConstruction(); + + public DescriptorProto(DescriptorProto other) : this() { + name_ = other.name_; + field_ = other.field_.Clone(); + extension_ = other.extension_.Clone(); + nestedType_ = other.nestedType_.Clone(); + enumType_ = other.enumType_.Clone(); + extensionRange_ = other.extensionRange_.Clone(); + oneofDecl_ = other.oneofDecl_.Clone(); + Options = other.options_ != null ? other.Options.Clone() : null; + reservedRange_ = other.reservedRange_.Clone(); + reservedName_ = other.reservedName_.Clone(); + } + + public DescriptorProto Clone() { + return new DescriptorProto(this); + } + + public const int NameFieldNumber = 1; + private string name_ = ""; + public string Name { + get { return name_; } + set { + name_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int FieldFieldNumber = 2; + private static readonly pb::FieldCodec _repeated_field_codec + = pb::FieldCodec.ForMessage(18, global::Google.Protobuf.Reflection.FieldDescriptorProto.Parser); + private readonly pbc::RepeatedField field_ = new pbc::RepeatedField(); + public pbc::RepeatedField Field { + get { return field_; } + } + + public const int ExtensionFieldNumber = 6; + private static readonly pb::FieldCodec _repeated_extension_codec + = pb::FieldCodec.ForMessage(50, global::Google.Protobuf.Reflection.FieldDescriptorProto.Parser); + private readonly pbc::RepeatedField extension_ = new pbc::RepeatedField(); + public pbc::RepeatedField Extension { + get { return extension_; } + } + + public const int NestedTypeFieldNumber = 3; + private static readonly pb::FieldCodec _repeated_nestedType_codec + = pb::FieldCodec.ForMessage(26, global::Google.Protobuf.Reflection.DescriptorProto.Parser); + private readonly pbc::RepeatedField nestedType_ = new pbc::RepeatedField(); + public pbc::RepeatedField NestedType { + get { return nestedType_; } + } + + public const int EnumTypeFieldNumber = 4; + private static readonly pb::FieldCodec _repeated_enumType_codec + = pb::FieldCodec.ForMessage(34, global::Google.Protobuf.Reflection.EnumDescriptorProto.Parser); + private readonly pbc::RepeatedField enumType_ = new pbc::RepeatedField(); + public pbc::RepeatedField EnumType { + get { return enumType_; } + } + + public const int ExtensionRangeFieldNumber = 5; + private static readonly pb::FieldCodec _repeated_extensionRange_codec + = pb::FieldCodec.ForMessage(42, global::Google.Protobuf.Reflection.DescriptorProto.Types.ExtensionRange.Parser); + private readonly pbc::RepeatedField extensionRange_ = new pbc::RepeatedField(); + public pbc::RepeatedField ExtensionRange { + get { return extensionRange_; } + } + + public const int OneofDeclFieldNumber = 8; + private static readonly pb::FieldCodec _repeated_oneofDecl_codec + = pb::FieldCodec.ForMessage(66, global::Google.Protobuf.Reflection.OneofDescriptorProto.Parser); + private readonly pbc::RepeatedField oneofDecl_ = new pbc::RepeatedField(); + public pbc::RepeatedField OneofDecl { + get { return oneofDecl_; } + } + + public const int OptionsFieldNumber = 7; + private global::Google.Protobuf.Reflection.MessageOptions options_; + public global::Google.Protobuf.Reflection.MessageOptions Options { + get { return options_; } + set { + options_ = value; + } + } + + public const int ReservedRangeFieldNumber = 9; + private static readonly pb::FieldCodec _repeated_reservedRange_codec + = pb::FieldCodec.ForMessage(74, global::Google.Protobuf.Reflection.DescriptorProto.Types.ReservedRange.Parser); + private readonly pbc::RepeatedField reservedRange_ = new pbc::RepeatedField(); + public pbc::RepeatedField ReservedRange { + get { return reservedRange_; } + } + + public const int ReservedNameFieldNumber = 10; + private static readonly pb::FieldCodec _repeated_reservedName_codec + = pb::FieldCodec.ForString(82); + private readonly pbc::RepeatedField reservedName_ = new pbc::RepeatedField(); + public pbc::RepeatedField ReservedName { + get { return reservedName_; } + } + + public override bool Equals(object other) { + return Equals(other as DescriptorProto); + } + + public bool Equals(DescriptorProto other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Name != other.Name) return false; + if(!field_.Equals(other.field_)) return false; + if(!extension_.Equals(other.extension_)) return false; + if(!nestedType_.Equals(other.nestedType_)) return false; + if(!enumType_.Equals(other.enumType_)) return false; + if(!extensionRange_.Equals(other.extensionRange_)) return false; + if(!oneofDecl_.Equals(other.oneofDecl_)) return false; + if (!object.Equals(Options, other.Options)) return false; + if(!reservedRange_.Equals(other.reservedRange_)) return false; + if(!reservedName_.Equals(other.reservedName_)) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (Name.Length != 0) hash ^= Name.GetHashCode(); + hash ^= field_.GetHashCode(); + hash ^= extension_.GetHashCode(); + hash ^= nestedType_.GetHashCode(); + hash ^= enumType_.GetHashCode(); + hash ^= extensionRange_.GetHashCode(); + hash ^= oneofDecl_.GetHashCode(); + if (options_ != null) hash ^= Options.GetHashCode(); + hash ^= reservedRange_.GetHashCode(); + hash ^= reservedName_.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (Name.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Name); + } + field_.WriteTo(output, _repeated_field_codec); + nestedType_.WriteTo(output, _repeated_nestedType_codec); + enumType_.WriteTo(output, _repeated_enumType_codec); + extensionRange_.WriteTo(output, _repeated_extensionRange_codec); + extension_.WriteTo(output, _repeated_extension_codec); + if (options_ != null) { + output.WriteRawTag(58); + output.WriteMessage(Options); + } + oneofDecl_.WriteTo(output, _repeated_oneofDecl_codec); + reservedRange_.WriteTo(output, _repeated_reservedRange_codec); + reservedName_.WriteTo(output, _repeated_reservedName_codec); + } + + public int CalculateSize() { + int size = 0; + if (Name.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); + } + size += field_.CalculateSize(_repeated_field_codec); + size += extension_.CalculateSize(_repeated_extension_codec); + size += nestedType_.CalculateSize(_repeated_nestedType_codec); + size += enumType_.CalculateSize(_repeated_enumType_codec); + size += extensionRange_.CalculateSize(_repeated_extensionRange_codec); + size += oneofDecl_.CalculateSize(_repeated_oneofDecl_codec); + if (options_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options); + } + size += reservedRange_.CalculateSize(_repeated_reservedRange_codec); + size += reservedName_.CalculateSize(_repeated_reservedName_codec); + return size; + } + + public void MergeFrom(DescriptorProto other) { + if (other == null) { + return; + } + if (other.Name.Length != 0) { + Name = other.Name; + } + field_.Add(other.field_); + extension_.Add(other.extension_); + nestedType_.Add(other.nestedType_); + enumType_.Add(other.enumType_); + extensionRange_.Add(other.extensionRange_); + oneofDecl_.Add(other.oneofDecl_); + if (other.options_ != null) { + if (options_ == null) { + options_ = new global::Google.Protobuf.Reflection.MessageOptions(); + } + Options.MergeFrom(other.Options); + } + reservedRange_.Add(other.reservedRange_); + reservedName_.Add(other.reservedName_); + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 10: { + Name = input.ReadString(); + break; + } + case 18: { + field_.AddEntriesFrom(input, _repeated_field_codec); + break; + } + case 26: { + nestedType_.AddEntriesFrom(input, _repeated_nestedType_codec); + break; + } + case 34: { + enumType_.AddEntriesFrom(input, _repeated_enumType_codec); + break; + } + case 42: { + extensionRange_.AddEntriesFrom(input, _repeated_extensionRange_codec); + break; + } + case 50: { + extension_.AddEntriesFrom(input, _repeated_extension_codec); + break; + } + case 58: { + if (options_ == null) { + options_ = new global::Google.Protobuf.Reflection.MessageOptions(); + } + input.ReadMessage(options_); + break; + } + case 66: { + oneofDecl_.AddEntriesFrom(input, _repeated_oneofDecl_codec); + break; + } + case 74: { + reservedRange_.AddEntriesFrom(input, _repeated_reservedRange_codec); + break; + } + case 82: { + reservedName_.AddEntriesFrom(input, _repeated_reservedName_codec); + break; + } + } + } + } + + #region Nested types + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public static partial class Types { + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + internal sealed partial class ExtensionRange : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new ExtensionRange()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorProto.Descriptor.NestedTypes[0]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public ExtensionRange() { + OnConstruction(); + } + + partial void OnConstruction(); + + public ExtensionRange(ExtensionRange other) : this() { + start_ = other.start_; + end_ = other.end_; + } + + public ExtensionRange Clone() { + return new ExtensionRange(this); + } + + public const int StartFieldNumber = 1; + private int start_; + public int Start { + get { return start_; } + set { + start_ = value; + } + } + + public const int EndFieldNumber = 2; + private int end_; + public int End { + get { return end_; } + set { + end_ = value; + } + } + + public override bool Equals(object other) { + return Equals(other as ExtensionRange); + } + + public bool Equals(ExtensionRange other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Start != other.Start) return false; + if (End != other.End) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (Start != 0) hash ^= Start.GetHashCode(); + if (End != 0) hash ^= End.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (Start != 0) { + output.WriteRawTag(8); + output.WriteInt32(Start); + } + if (End != 0) { + output.WriteRawTag(16); + output.WriteInt32(End); + } + } + + public int CalculateSize() { + int size = 0; + if (Start != 0) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Start); + } + if (End != 0) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(End); + } + return size; + } + + public void MergeFrom(ExtensionRange other) { + if (other == null) { + return; + } + if (other.Start != 0) { + Start = other.Start; + } + if (other.End != 0) { + End = other.End; + } + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 8: { + Start = input.ReadInt32(); + break; + } + case 16: { + End = input.ReadInt32(); + break; + } + } + } + } + + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + internal sealed partial class ReservedRange : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new ReservedRange()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorProto.Descriptor.NestedTypes[1]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public ReservedRange() { + OnConstruction(); + } + + partial void OnConstruction(); + + public ReservedRange(ReservedRange other) : this() { + start_ = other.start_; + end_ = other.end_; + } + + public ReservedRange Clone() { + return new ReservedRange(this); + } + + public const int StartFieldNumber = 1; + private int start_; + public int Start { + get { return start_; } + set { + start_ = value; + } + } + + public const int EndFieldNumber = 2; + private int end_; + public int End { + get { return end_; } + set { + end_ = value; + } + } + + public override bool Equals(object other) { + return Equals(other as ReservedRange); + } + + public bool Equals(ReservedRange other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Start != other.Start) return false; + if (End != other.End) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (Start != 0) hash ^= Start.GetHashCode(); + if (End != 0) hash ^= End.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (Start != 0) { + output.WriteRawTag(8); + output.WriteInt32(Start); + } + if (End != 0) { + output.WriteRawTag(16); + output.WriteInt32(End); + } + } + + public int CalculateSize() { + int size = 0; + if (Start != 0) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Start); + } + if (End != 0) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(End); + } + return size; + } + + public void MergeFrom(ReservedRange other) { + if (other == null) { + return; + } + if (other.Start != 0) { + Start = other.Start; + } + if (other.End != 0) { + End = other.End; + } + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 8: { + Start = input.ReadInt32(); + break; + } + case 16: { + End = input.ReadInt32(); + break; + } + } + } + } + + } + + } + #endregion + + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + internal sealed partial class FieldDescriptorProto : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new FieldDescriptorProto()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorProtoFile.Descriptor.MessageTypes[3]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public FieldDescriptorProto() { + OnConstruction(); + } + + partial void OnConstruction(); + + public FieldDescriptorProto(FieldDescriptorProto other) : this() { + name_ = other.name_; + number_ = other.number_; + label_ = other.label_; + type_ = other.type_; + typeName_ = other.typeName_; + extendee_ = other.extendee_; + defaultValue_ = other.defaultValue_; + oneofIndex_ = other.oneofIndex_; + Options = other.options_ != null ? other.Options.Clone() : null; + } + + public FieldDescriptorProto Clone() { + return new FieldDescriptorProto(this); + } + + public const int NameFieldNumber = 1; + private string name_ = ""; + public string Name { + get { return name_; } + set { + name_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int NumberFieldNumber = 3; + private int number_; + public int Number { + get { return number_; } + set { + number_ = value; + } + } + + public const int LabelFieldNumber = 4; + private global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Label label_ = global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Label.LABEL_OPTIONAL; + public global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Label Label { + get { return label_; } + set { + label_ = value; + } + } + + public const int TypeFieldNumber = 5; + private global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Type type_ = global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Type.TYPE_DOUBLE; + public global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Type Type { + get { return type_; } + set { + type_ = value; + } + } + + public const int TypeNameFieldNumber = 6; + private string typeName_ = ""; + public string TypeName { + get { return typeName_; } + set { + typeName_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int ExtendeeFieldNumber = 2; + private string extendee_ = ""; + public string Extendee { + get { return extendee_; } + set { + extendee_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int DefaultValueFieldNumber = 7; + private string defaultValue_ = ""; + public string DefaultValue { + get { return defaultValue_; } + set { + defaultValue_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int OneofIndexFieldNumber = 9; + private int oneofIndex_; + public int OneofIndex { + get { return oneofIndex_; } + set { + oneofIndex_ = value; + } + } + + public const int OptionsFieldNumber = 8; + private global::Google.Protobuf.Reflection.FieldOptions options_; + public global::Google.Protobuf.Reflection.FieldOptions Options { + get { return options_; } + set { + options_ = value; + } + } + + public override bool Equals(object other) { + return Equals(other as FieldDescriptorProto); + } + + public bool Equals(FieldDescriptorProto other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Name != other.Name) return false; + if (Number != other.Number) return false; + if (Label != other.Label) return false; + if (Type != other.Type) return false; + if (TypeName != other.TypeName) return false; + if (Extendee != other.Extendee) return false; + if (DefaultValue != other.DefaultValue) return false; + if (OneofIndex != other.OneofIndex) return false; + if (!object.Equals(Options, other.Options)) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (Name.Length != 0) hash ^= Name.GetHashCode(); + if (Number != 0) hash ^= Number.GetHashCode(); + if (Label != global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Label.LABEL_OPTIONAL) hash ^= Label.GetHashCode(); + if (Type != global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Type.TYPE_DOUBLE) hash ^= Type.GetHashCode(); + if (TypeName.Length != 0) hash ^= TypeName.GetHashCode(); + if (Extendee.Length != 0) hash ^= Extendee.GetHashCode(); + if (DefaultValue.Length != 0) hash ^= DefaultValue.GetHashCode(); + if (OneofIndex != 0) hash ^= OneofIndex.GetHashCode(); + if (options_ != null) hash ^= Options.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (Name.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Name); + } + if (Extendee.Length != 0) { + output.WriteRawTag(18); + output.WriteString(Extendee); + } + if (Number != 0) { + output.WriteRawTag(24); + output.WriteInt32(Number); + } + if (Label != global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Label.LABEL_OPTIONAL) { + output.WriteRawTag(32); + output.WriteEnum((int) Label); + } + if (Type != global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Type.TYPE_DOUBLE) { + output.WriteRawTag(40); + output.WriteEnum((int) Type); + } + if (TypeName.Length != 0) { + output.WriteRawTag(50); + output.WriteString(TypeName); + } + if (DefaultValue.Length != 0) { + output.WriteRawTag(58); + output.WriteString(DefaultValue); + } + if (options_ != null) { + output.WriteRawTag(66); + output.WriteMessage(Options); + } + if (OneofIndex != 0) { + output.WriteRawTag(72); + output.WriteInt32(OneofIndex); + } + } + + public int CalculateSize() { + int size = 0; + if (Name.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); + } + if (Number != 0) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Number); + } + if (Label != global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Label.LABEL_OPTIONAL) { + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Label); + } + if (Type != global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Type.TYPE_DOUBLE) { + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type); + } + if (TypeName.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(TypeName); + } + if (Extendee.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Extendee); + } + if (DefaultValue.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(DefaultValue); + } + if (OneofIndex != 0) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(OneofIndex); + } + if (options_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options); + } + return size; + } + + public void MergeFrom(FieldDescriptorProto other) { + if (other == null) { + return; + } + if (other.Name.Length != 0) { + Name = other.Name; + } + if (other.Number != 0) { + Number = other.Number; + } + if (other.Label != global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Label.LABEL_OPTIONAL) { + Label = other.Label; + } + if (other.Type != global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Type.TYPE_DOUBLE) { + Type = other.Type; + } + if (other.TypeName.Length != 0) { + TypeName = other.TypeName; + } + if (other.Extendee.Length != 0) { + Extendee = other.Extendee; + } + if (other.DefaultValue.Length != 0) { + DefaultValue = other.DefaultValue; + } + if (other.OneofIndex != 0) { + OneofIndex = other.OneofIndex; + } + if (other.options_ != null) { + if (options_ == null) { + options_ = new global::Google.Protobuf.Reflection.FieldOptions(); + } + Options.MergeFrom(other.Options); + } + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 10: { + Name = input.ReadString(); + break; + } + case 18: { + Extendee = input.ReadString(); + break; + } + case 24: { + Number = input.ReadInt32(); + break; + } + case 32: { + label_ = (global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Label) input.ReadEnum(); + break; + } + case 40: { + type_ = (global::Google.Protobuf.Reflection.FieldDescriptorProto.Types.Type) input.ReadEnum(); + break; + } + case 50: { + TypeName = input.ReadString(); + break; + } + case 58: { + DefaultValue = input.ReadString(); + break; + } + case 66: { + if (options_ == null) { + options_ = new global::Google.Protobuf.Reflection.FieldOptions(); + } + input.ReadMessage(options_); + break; + } + case 72: { + OneofIndex = input.ReadInt32(); + break; + } + } + } + } + + #region Nested types + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public static partial class Types { + internal enum Type { + TYPE_DOUBLE = 1, + TYPE_FLOAT = 2, + TYPE_INT64 = 3, + TYPE_UINT64 = 4, + TYPE_INT32 = 5, + TYPE_FIXED64 = 6, + TYPE_FIXED32 = 7, + TYPE_BOOL = 8, + TYPE_STRING = 9, + TYPE_GROUP = 10, + TYPE_MESSAGE = 11, + TYPE_BYTES = 12, + TYPE_UINT32 = 13, + TYPE_ENUM = 14, + TYPE_SFIXED32 = 15, + TYPE_SFIXED64 = 16, + TYPE_SINT32 = 17, + TYPE_SINT64 = 18, + } + + internal enum Label { + LABEL_OPTIONAL = 1, + LABEL_REQUIRED = 2, + LABEL_REPEATED = 3, + } + + } + #endregion + + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + internal sealed partial class OneofDescriptorProto : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new OneofDescriptorProto()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorProtoFile.Descriptor.MessageTypes[4]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public OneofDescriptorProto() { + OnConstruction(); + } + + partial void OnConstruction(); + + public OneofDescriptorProto(OneofDescriptorProto other) : this() { + name_ = other.name_; + } + + public OneofDescriptorProto Clone() { + return new OneofDescriptorProto(this); + } + + public const int NameFieldNumber = 1; + private string name_ = ""; + public string Name { + get { return name_; } + set { + name_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public override bool Equals(object other) { + return Equals(other as OneofDescriptorProto); + } + + public bool Equals(OneofDescriptorProto other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Name != other.Name) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (Name.Length != 0) hash ^= Name.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (Name.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Name); + } + } + + public int CalculateSize() { + int size = 0; + if (Name.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); + } + return size; + } + + public void MergeFrom(OneofDescriptorProto other) { + if (other == null) { + return; + } + if (other.Name.Length != 0) { + Name = other.Name; + } + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 10: { + Name = input.ReadString(); + break; + } + } + } + } + + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + internal sealed partial class EnumDescriptorProto : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new EnumDescriptorProto()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorProtoFile.Descriptor.MessageTypes[5]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public EnumDescriptorProto() { + OnConstruction(); + } + + partial void OnConstruction(); + + public EnumDescriptorProto(EnumDescriptorProto other) : this() { + name_ = other.name_; + value_ = other.value_.Clone(); + Options = other.options_ != null ? other.Options.Clone() : null; + } + + public EnumDescriptorProto Clone() { + return new EnumDescriptorProto(this); + } + + public const int NameFieldNumber = 1; + private string name_ = ""; + public string Name { + get { return name_; } + set { + name_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int ValueFieldNumber = 2; + private static readonly pb::FieldCodec _repeated_value_codec + = pb::FieldCodec.ForMessage(18, global::Google.Protobuf.Reflection.EnumValueDescriptorProto.Parser); + private readonly pbc::RepeatedField value_ = new pbc::RepeatedField(); + public pbc::RepeatedField Value { + get { return value_; } + } + + public const int OptionsFieldNumber = 3; + private global::Google.Protobuf.Reflection.EnumOptions options_; + public global::Google.Protobuf.Reflection.EnumOptions Options { + get { return options_; } + set { + options_ = value; + } + } + + public override bool Equals(object other) { + return Equals(other as EnumDescriptorProto); + } + + public bool Equals(EnumDescriptorProto other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Name != other.Name) return false; + if(!value_.Equals(other.value_)) return false; + if (!object.Equals(Options, other.Options)) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (Name.Length != 0) hash ^= Name.GetHashCode(); + hash ^= value_.GetHashCode(); + if (options_ != null) hash ^= Options.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (Name.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Name); + } + value_.WriteTo(output, _repeated_value_codec); + if (options_ != null) { + output.WriteRawTag(26); + output.WriteMessage(Options); + } + } + + public int CalculateSize() { + int size = 0; + if (Name.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); + } + size += value_.CalculateSize(_repeated_value_codec); + if (options_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options); + } + return size; + } + + public void MergeFrom(EnumDescriptorProto other) { + if (other == null) { + return; + } + if (other.Name.Length != 0) { + Name = other.Name; + } + value_.Add(other.value_); + if (other.options_ != null) { + if (options_ == null) { + options_ = new global::Google.Protobuf.Reflection.EnumOptions(); + } + Options.MergeFrom(other.Options); + } + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 10: { + Name = input.ReadString(); + break; + } + case 18: { + value_.AddEntriesFrom(input, _repeated_value_codec); + break; + } + case 26: { + if (options_ == null) { + options_ = new global::Google.Protobuf.Reflection.EnumOptions(); + } + input.ReadMessage(options_); + break; + } + } + } + } + + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + internal sealed partial class EnumValueDescriptorProto : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new EnumValueDescriptorProto()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorProtoFile.Descriptor.MessageTypes[6]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public EnumValueDescriptorProto() { + OnConstruction(); + } + + partial void OnConstruction(); + + public EnumValueDescriptorProto(EnumValueDescriptorProto other) : this() { + name_ = other.name_; + number_ = other.number_; + Options = other.options_ != null ? other.Options.Clone() : null; + } + + public EnumValueDescriptorProto Clone() { + return new EnumValueDescriptorProto(this); + } + + public const int NameFieldNumber = 1; + private string name_ = ""; + public string Name { + get { return name_; } + set { + name_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int NumberFieldNumber = 2; + private int number_; + public int Number { + get { return number_; } + set { + number_ = value; + } + } + + public const int OptionsFieldNumber = 3; + private global::Google.Protobuf.Reflection.EnumValueOptions options_; + public global::Google.Protobuf.Reflection.EnumValueOptions Options { + get { return options_; } + set { + options_ = value; + } + } + + public override bool Equals(object other) { + return Equals(other as EnumValueDescriptorProto); + } + + public bool Equals(EnumValueDescriptorProto other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Name != other.Name) return false; + if (Number != other.Number) return false; + if (!object.Equals(Options, other.Options)) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (Name.Length != 0) hash ^= Name.GetHashCode(); + if (Number != 0) hash ^= Number.GetHashCode(); + if (options_ != null) hash ^= Options.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (Name.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Name); + } + if (Number != 0) { + output.WriteRawTag(16); + output.WriteInt32(Number); + } + if (options_ != null) { + output.WriteRawTag(26); + output.WriteMessage(Options); + } + } + + public int CalculateSize() { + int size = 0; + if (Name.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); + } + if (Number != 0) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Number); + } + if (options_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options); + } + return size; + } + + public void MergeFrom(EnumValueDescriptorProto other) { + if (other == null) { + return; + } + if (other.Name.Length != 0) { + Name = other.Name; + } + if (other.Number != 0) { + Number = other.Number; + } + if (other.options_ != null) { + if (options_ == null) { + options_ = new global::Google.Protobuf.Reflection.EnumValueOptions(); + } + Options.MergeFrom(other.Options); + } + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 10: { + Name = input.ReadString(); + break; + } + case 16: { + Number = input.ReadInt32(); + break; + } + case 26: { + if (options_ == null) { + options_ = new global::Google.Protobuf.Reflection.EnumValueOptions(); + } + input.ReadMessage(options_); + break; + } + } + } + } + + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + internal sealed partial class ServiceDescriptorProto : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new ServiceDescriptorProto()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorProtoFile.Descriptor.MessageTypes[7]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public ServiceDescriptorProto() { + OnConstruction(); + } + + partial void OnConstruction(); + + public ServiceDescriptorProto(ServiceDescriptorProto other) : this() { + name_ = other.name_; + method_ = other.method_.Clone(); + Options = other.options_ != null ? other.Options.Clone() : null; + } + + public ServiceDescriptorProto Clone() { + return new ServiceDescriptorProto(this); + } + + public const int NameFieldNumber = 1; + private string name_ = ""; + public string Name { + get { return name_; } + set { + name_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int MethodFieldNumber = 2; + private static readonly pb::FieldCodec _repeated_method_codec + = pb::FieldCodec.ForMessage(18, global::Google.Protobuf.Reflection.MethodDescriptorProto.Parser); + private readonly pbc::RepeatedField method_ = new pbc::RepeatedField(); + public pbc::RepeatedField Method { + get { return method_; } + } + + public const int OptionsFieldNumber = 3; + private global::Google.Protobuf.Reflection.ServiceOptions options_; + public global::Google.Protobuf.Reflection.ServiceOptions Options { + get { return options_; } + set { + options_ = value; + } + } + + public override bool Equals(object other) { + return Equals(other as ServiceDescriptorProto); + } + + public bool Equals(ServiceDescriptorProto other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Name != other.Name) return false; + if(!method_.Equals(other.method_)) return false; + if (!object.Equals(Options, other.Options)) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (Name.Length != 0) hash ^= Name.GetHashCode(); + hash ^= method_.GetHashCode(); + if (options_ != null) hash ^= Options.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (Name.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Name); + } + method_.WriteTo(output, _repeated_method_codec); + if (options_ != null) { + output.WriteRawTag(26); + output.WriteMessage(Options); + } + } + + public int CalculateSize() { + int size = 0; + if (Name.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); + } + size += method_.CalculateSize(_repeated_method_codec); + if (options_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options); + } + return size; + } + + public void MergeFrom(ServiceDescriptorProto other) { + if (other == null) { + return; + } + if (other.Name.Length != 0) { + Name = other.Name; + } + method_.Add(other.method_); + if (other.options_ != null) { + if (options_ == null) { + options_ = new global::Google.Protobuf.Reflection.ServiceOptions(); + } + Options.MergeFrom(other.Options); + } + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 10: { + Name = input.ReadString(); + break; + } + case 18: { + method_.AddEntriesFrom(input, _repeated_method_codec); + break; + } + case 26: { + if (options_ == null) { + options_ = new global::Google.Protobuf.Reflection.ServiceOptions(); + } + input.ReadMessage(options_); + break; + } + } + } + } + + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + internal sealed partial class MethodDescriptorProto : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new MethodDescriptorProto()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorProtoFile.Descriptor.MessageTypes[8]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public MethodDescriptorProto() { + OnConstruction(); + } + + partial void OnConstruction(); + + public MethodDescriptorProto(MethodDescriptorProto other) : this() { + name_ = other.name_; + inputType_ = other.inputType_; + outputType_ = other.outputType_; + Options = other.options_ != null ? other.Options.Clone() : null; + clientStreaming_ = other.clientStreaming_; + serverStreaming_ = other.serverStreaming_; + } + + public MethodDescriptorProto Clone() { + return new MethodDescriptorProto(this); + } + + public const int NameFieldNumber = 1; + private string name_ = ""; + public string Name { + get { return name_; } + set { + name_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int InputTypeFieldNumber = 2; + private string inputType_ = ""; + public string InputType { + get { return inputType_; } + set { + inputType_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int OutputTypeFieldNumber = 3; + private string outputType_ = ""; + public string OutputType { + get { return outputType_; } + set { + outputType_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int OptionsFieldNumber = 4; + private global::Google.Protobuf.Reflection.MethodOptions options_; + public global::Google.Protobuf.Reflection.MethodOptions Options { + get { return options_; } + set { + options_ = value; + } + } + + public const int ClientStreamingFieldNumber = 5; + private bool clientStreaming_; + public bool ClientStreaming { + get { return clientStreaming_; } + set { + clientStreaming_ = value; + } + } + + public const int ServerStreamingFieldNumber = 6; + private bool serverStreaming_; + public bool ServerStreaming { + get { return serverStreaming_; } + set { + serverStreaming_ = value; + } + } + + public override bool Equals(object other) { + return Equals(other as MethodDescriptorProto); + } + + public bool Equals(MethodDescriptorProto other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Name != other.Name) return false; + if (InputType != other.InputType) return false; + if (OutputType != other.OutputType) return false; + if (!object.Equals(Options, other.Options)) return false; + if (ClientStreaming != other.ClientStreaming) return false; + if (ServerStreaming != other.ServerStreaming) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (Name.Length != 0) hash ^= Name.GetHashCode(); + if (InputType.Length != 0) hash ^= InputType.GetHashCode(); + if (OutputType.Length != 0) hash ^= OutputType.GetHashCode(); + if (options_ != null) hash ^= Options.GetHashCode(); + if (ClientStreaming != false) hash ^= ClientStreaming.GetHashCode(); + if (ServerStreaming != false) hash ^= ServerStreaming.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (Name.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Name); + } + if (InputType.Length != 0) { + output.WriteRawTag(18); + output.WriteString(InputType); + } + if (OutputType.Length != 0) { + output.WriteRawTag(26); + output.WriteString(OutputType); + } + if (options_ != null) { + output.WriteRawTag(34); + output.WriteMessage(Options); + } + if (ClientStreaming != false) { + output.WriteRawTag(40); + output.WriteBool(ClientStreaming); + } + if (ServerStreaming != false) { + output.WriteRawTag(48); + output.WriteBool(ServerStreaming); + } + } + + public int CalculateSize() { + int size = 0; + if (Name.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); + } + if (InputType.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(InputType); + } + if (OutputType.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(OutputType); + } + if (options_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(Options); + } + if (ClientStreaming != false) { + size += 1 + 1; + } + if (ServerStreaming != false) { + size += 1 + 1; + } + return size; + } + + public void MergeFrom(MethodDescriptorProto other) { + if (other == null) { + return; + } + if (other.Name.Length != 0) { + Name = other.Name; + } + if (other.InputType.Length != 0) { + InputType = other.InputType; + } + if (other.OutputType.Length != 0) { + OutputType = other.OutputType; + } + if (other.options_ != null) { + if (options_ == null) { + options_ = new global::Google.Protobuf.Reflection.MethodOptions(); + } + Options.MergeFrom(other.Options); + } + if (other.ClientStreaming != false) { + ClientStreaming = other.ClientStreaming; + } + if (other.ServerStreaming != false) { + ServerStreaming = other.ServerStreaming; + } + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 10: { + Name = input.ReadString(); + break; + } + case 18: { + InputType = input.ReadString(); + break; + } + case 26: { + OutputType = input.ReadString(); + break; + } + case 34: { + if (options_ == null) { + options_ = new global::Google.Protobuf.Reflection.MethodOptions(); + } + input.ReadMessage(options_); + break; + } + case 40: { + ClientStreaming = input.ReadBool(); + break; + } + case 48: { + ServerStreaming = input.ReadBool(); + break; + } + } + } + } + + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + internal sealed partial class FileOptions : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new FileOptions()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorProtoFile.Descriptor.MessageTypes[9]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public FileOptions() { + OnConstruction(); + } + + partial void OnConstruction(); + + public FileOptions(FileOptions other) : this() { + javaPackage_ = other.javaPackage_; + javaOuterClassname_ = other.javaOuterClassname_; + javaMultipleFiles_ = other.javaMultipleFiles_; + javaGenerateEqualsAndHash_ = other.javaGenerateEqualsAndHash_; + javaStringCheckUtf8_ = other.javaStringCheckUtf8_; + optimizeFor_ = other.optimizeFor_; + goPackage_ = other.goPackage_; + ccGenericServices_ = other.ccGenericServices_; + javaGenericServices_ = other.javaGenericServices_; + pyGenericServices_ = other.pyGenericServices_; + deprecated_ = other.deprecated_; + ccEnableArenas_ = other.ccEnableArenas_; + objcClassPrefix_ = other.objcClassPrefix_; + csharpNamespace_ = other.csharpNamespace_; + javananoUseDeprecatedPackage_ = other.javananoUseDeprecatedPackage_; + uninterpretedOption_ = other.uninterpretedOption_.Clone(); + } + + public FileOptions Clone() { + return new FileOptions(this); + } + + public const int JavaPackageFieldNumber = 1; + private string javaPackage_ = ""; + public string JavaPackage { + get { return javaPackage_; } + set { + javaPackage_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int JavaOuterClassnameFieldNumber = 8; + private string javaOuterClassname_ = ""; + public string JavaOuterClassname { + get { return javaOuterClassname_; } + set { + javaOuterClassname_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int JavaMultipleFilesFieldNumber = 10; + private bool javaMultipleFiles_; + public bool JavaMultipleFiles { + get { return javaMultipleFiles_; } + set { + javaMultipleFiles_ = value; + } + } + + public const int JavaGenerateEqualsAndHashFieldNumber = 20; + private bool javaGenerateEqualsAndHash_; + public bool JavaGenerateEqualsAndHash { + get { return javaGenerateEqualsAndHash_; } + set { + javaGenerateEqualsAndHash_ = value; + } + } + + public const int JavaStringCheckUtf8FieldNumber = 27; + private bool javaStringCheckUtf8_; + public bool JavaStringCheckUtf8 { + get { return javaStringCheckUtf8_; } + set { + javaStringCheckUtf8_ = value; + } + } + + public const int OptimizeForFieldNumber = 9; + private global::Google.Protobuf.Reflection.FileOptions.Types.OptimizeMode optimizeFor_ = global::Google.Protobuf.Reflection.FileOptions.Types.OptimizeMode.SPEED; + public global::Google.Protobuf.Reflection.FileOptions.Types.OptimizeMode OptimizeFor { + get { return optimizeFor_; } + set { + optimizeFor_ = value; + } + } + + public const int GoPackageFieldNumber = 11; + private string goPackage_ = ""; + public string GoPackage { + get { return goPackage_; } + set { + goPackage_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int CcGenericServicesFieldNumber = 16; + private bool ccGenericServices_; + public bool CcGenericServices { + get { return ccGenericServices_; } + set { + ccGenericServices_ = value; + } + } + + public const int JavaGenericServicesFieldNumber = 17; + private bool javaGenericServices_; + public bool JavaGenericServices { + get { return javaGenericServices_; } + set { + javaGenericServices_ = value; + } + } + + public const int PyGenericServicesFieldNumber = 18; + private bool pyGenericServices_; + public bool PyGenericServices { + get { return pyGenericServices_; } + set { + pyGenericServices_ = value; + } + } + + public const int DeprecatedFieldNumber = 23; + private bool deprecated_; + public bool Deprecated { + get { return deprecated_; } + set { + deprecated_ = value; + } + } + + public const int CcEnableArenasFieldNumber = 31; + private bool ccEnableArenas_; + public bool CcEnableArenas { + get { return ccEnableArenas_; } + set { + ccEnableArenas_ = value; + } + } + + public const int ObjcClassPrefixFieldNumber = 36; + private string objcClassPrefix_ = ""; + public string ObjcClassPrefix { + get { return objcClassPrefix_; } + set { + objcClassPrefix_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int CsharpNamespaceFieldNumber = 37; + private string csharpNamespace_ = ""; + public string CsharpNamespace { + get { return csharpNamespace_; } + set { + csharpNamespace_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int JavananoUseDeprecatedPackageFieldNumber = 38; + private bool javananoUseDeprecatedPackage_; + public bool JavananoUseDeprecatedPackage { + get { return javananoUseDeprecatedPackage_; } + set { + javananoUseDeprecatedPackage_ = value; + } + } + + public const int UninterpretedOptionFieldNumber = 999; + private static readonly pb::FieldCodec _repeated_uninterpretedOption_codec + = pb::FieldCodec.ForMessage(7994, global::Google.Protobuf.Reflection.UninterpretedOption.Parser); + private readonly pbc::RepeatedField uninterpretedOption_ = new pbc::RepeatedField(); + public pbc::RepeatedField UninterpretedOption { + get { return uninterpretedOption_; } + } + + public override bool Equals(object other) { + return Equals(other as FileOptions); + } + + public bool Equals(FileOptions other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (JavaPackage != other.JavaPackage) return false; + if (JavaOuterClassname != other.JavaOuterClassname) return false; + if (JavaMultipleFiles != other.JavaMultipleFiles) return false; + if (JavaGenerateEqualsAndHash != other.JavaGenerateEqualsAndHash) return false; + if (JavaStringCheckUtf8 != other.JavaStringCheckUtf8) return false; + if (OptimizeFor != other.OptimizeFor) return false; + if (GoPackage != other.GoPackage) return false; + if (CcGenericServices != other.CcGenericServices) return false; + if (JavaGenericServices != other.JavaGenericServices) return false; + if (PyGenericServices != other.PyGenericServices) return false; + if (Deprecated != other.Deprecated) return false; + if (CcEnableArenas != other.CcEnableArenas) return false; + if (ObjcClassPrefix != other.ObjcClassPrefix) return false; + if (CsharpNamespace != other.CsharpNamespace) return false; + if (JavananoUseDeprecatedPackage != other.JavananoUseDeprecatedPackage) return false; + if(!uninterpretedOption_.Equals(other.uninterpretedOption_)) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (JavaPackage.Length != 0) hash ^= JavaPackage.GetHashCode(); + if (JavaOuterClassname.Length != 0) hash ^= JavaOuterClassname.GetHashCode(); + if (JavaMultipleFiles != false) hash ^= JavaMultipleFiles.GetHashCode(); + if (JavaGenerateEqualsAndHash != false) hash ^= JavaGenerateEqualsAndHash.GetHashCode(); + if (JavaStringCheckUtf8 != false) hash ^= JavaStringCheckUtf8.GetHashCode(); + if (OptimizeFor != global::Google.Protobuf.Reflection.FileOptions.Types.OptimizeMode.SPEED) hash ^= OptimizeFor.GetHashCode(); + if (GoPackage.Length != 0) hash ^= GoPackage.GetHashCode(); + if (CcGenericServices != false) hash ^= CcGenericServices.GetHashCode(); + if (JavaGenericServices != false) hash ^= JavaGenericServices.GetHashCode(); + if (PyGenericServices != false) hash ^= PyGenericServices.GetHashCode(); + if (Deprecated != false) hash ^= Deprecated.GetHashCode(); + if (CcEnableArenas != false) hash ^= CcEnableArenas.GetHashCode(); + if (ObjcClassPrefix.Length != 0) hash ^= ObjcClassPrefix.GetHashCode(); + if (CsharpNamespace.Length != 0) hash ^= CsharpNamespace.GetHashCode(); + if (JavananoUseDeprecatedPackage != false) hash ^= JavananoUseDeprecatedPackage.GetHashCode(); + hash ^= uninterpretedOption_.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (JavaPackage.Length != 0) { + output.WriteRawTag(10); + output.WriteString(JavaPackage); + } + if (JavaOuterClassname.Length != 0) { + output.WriteRawTag(66); + output.WriteString(JavaOuterClassname); + } + if (OptimizeFor != global::Google.Protobuf.Reflection.FileOptions.Types.OptimizeMode.SPEED) { + output.WriteRawTag(72); + output.WriteEnum((int) OptimizeFor); + } + if (JavaMultipleFiles != false) { + output.WriteRawTag(80); + output.WriteBool(JavaMultipleFiles); + } + if (GoPackage.Length != 0) { + output.WriteRawTag(90); + output.WriteString(GoPackage); + } + if (CcGenericServices != false) { + output.WriteRawTag(128, 1); + output.WriteBool(CcGenericServices); + } + if (JavaGenericServices != false) { + output.WriteRawTag(136, 1); + output.WriteBool(JavaGenericServices); + } + if (PyGenericServices != false) { + output.WriteRawTag(144, 1); + output.WriteBool(PyGenericServices); + } + if (JavaGenerateEqualsAndHash != false) { + output.WriteRawTag(160, 1); + output.WriteBool(JavaGenerateEqualsAndHash); + } + if (Deprecated != false) { + output.WriteRawTag(184, 1); + output.WriteBool(Deprecated); + } + if (JavaStringCheckUtf8 != false) { + output.WriteRawTag(216, 1); + output.WriteBool(JavaStringCheckUtf8); + } + if (CcEnableArenas != false) { + output.WriteRawTag(248, 1); + output.WriteBool(CcEnableArenas); + } + if (ObjcClassPrefix.Length != 0) { + output.WriteRawTag(162, 2); + output.WriteString(ObjcClassPrefix); + } + if (CsharpNamespace.Length != 0) { + output.WriteRawTag(170, 2); + output.WriteString(CsharpNamespace); + } + if (JavananoUseDeprecatedPackage != false) { + output.WriteRawTag(176, 2); + output.WriteBool(JavananoUseDeprecatedPackage); + } + uninterpretedOption_.WriteTo(output, _repeated_uninterpretedOption_codec); + } + + public int CalculateSize() { + int size = 0; + if (JavaPackage.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(JavaPackage); + } + if (JavaOuterClassname.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(JavaOuterClassname); + } + if (JavaMultipleFiles != false) { + size += 1 + 1; + } + if (JavaGenerateEqualsAndHash != false) { + size += 2 + 1; + } + if (JavaStringCheckUtf8 != false) { + size += 2 + 1; + } + if (OptimizeFor != global::Google.Protobuf.Reflection.FileOptions.Types.OptimizeMode.SPEED) { + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) OptimizeFor); + } + if (GoPackage.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(GoPackage); + } + if (CcGenericServices != false) { + size += 2 + 1; + } + if (JavaGenericServices != false) { + size += 2 + 1; + } + if (PyGenericServices != false) { + size += 2 + 1; + } + if (Deprecated != false) { + size += 2 + 1; + } + if (CcEnableArenas != false) { + size += 2 + 1; + } + if (ObjcClassPrefix.Length != 0) { + size += 2 + pb::CodedOutputStream.ComputeStringSize(ObjcClassPrefix); + } + if (CsharpNamespace.Length != 0) { + size += 2 + pb::CodedOutputStream.ComputeStringSize(CsharpNamespace); + } + if (JavananoUseDeprecatedPackage != false) { + size += 2 + 1; + } + size += uninterpretedOption_.CalculateSize(_repeated_uninterpretedOption_codec); + return size; + } + + public void MergeFrom(FileOptions other) { + if (other == null) { + return; + } + if (other.JavaPackage.Length != 0) { + JavaPackage = other.JavaPackage; + } + if (other.JavaOuterClassname.Length != 0) { + JavaOuterClassname = other.JavaOuterClassname; + } + if (other.JavaMultipleFiles != false) { + JavaMultipleFiles = other.JavaMultipleFiles; + } + if (other.JavaGenerateEqualsAndHash != false) { + JavaGenerateEqualsAndHash = other.JavaGenerateEqualsAndHash; + } + if (other.JavaStringCheckUtf8 != false) { + JavaStringCheckUtf8 = other.JavaStringCheckUtf8; + } + if (other.OptimizeFor != global::Google.Protobuf.Reflection.FileOptions.Types.OptimizeMode.SPEED) { + OptimizeFor = other.OptimizeFor; + } + if (other.GoPackage.Length != 0) { + GoPackage = other.GoPackage; + } + if (other.CcGenericServices != false) { + CcGenericServices = other.CcGenericServices; + } + if (other.JavaGenericServices != false) { + JavaGenericServices = other.JavaGenericServices; + } + if (other.PyGenericServices != false) { + PyGenericServices = other.PyGenericServices; + } + if (other.Deprecated != false) { + Deprecated = other.Deprecated; + } + if (other.CcEnableArenas != false) { + CcEnableArenas = other.CcEnableArenas; + } + if (other.ObjcClassPrefix.Length != 0) { + ObjcClassPrefix = other.ObjcClassPrefix; + } + if (other.CsharpNamespace.Length != 0) { + CsharpNamespace = other.CsharpNamespace; + } + if (other.JavananoUseDeprecatedPackage != false) { + JavananoUseDeprecatedPackage = other.JavananoUseDeprecatedPackage; + } + uninterpretedOption_.Add(other.uninterpretedOption_); + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 10: { + JavaPackage = input.ReadString(); + break; + } + case 66: { + JavaOuterClassname = input.ReadString(); + break; + } + case 72: { + optimizeFor_ = (global::Google.Protobuf.Reflection.FileOptions.Types.OptimizeMode) input.ReadEnum(); + break; + } + case 80: { + JavaMultipleFiles = input.ReadBool(); + break; + } + case 90: { + GoPackage = input.ReadString(); + break; + } + case 128: { + CcGenericServices = input.ReadBool(); + break; + } + case 136: { + JavaGenericServices = input.ReadBool(); + break; + } + case 144: { + PyGenericServices = input.ReadBool(); + break; + } + case 160: { + JavaGenerateEqualsAndHash = input.ReadBool(); + break; + } + case 184: { + Deprecated = input.ReadBool(); + break; + } + case 216: { + JavaStringCheckUtf8 = input.ReadBool(); + break; + } + case 248: { + CcEnableArenas = input.ReadBool(); + break; + } + case 290: { + ObjcClassPrefix = input.ReadString(); + break; + } + case 298: { + CsharpNamespace = input.ReadString(); + break; + } + case 304: { + JavananoUseDeprecatedPackage = input.ReadBool(); + break; + } + case 7994: { + uninterpretedOption_.AddEntriesFrom(input, _repeated_uninterpretedOption_codec); + break; + } + } + } + } + + #region Nested types + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public static partial class Types { + internal enum OptimizeMode { + SPEED = 1, + CODE_SIZE = 2, + LITE_RUNTIME = 3, + } + + } + #endregion + + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + internal sealed partial class MessageOptions : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new MessageOptions()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorProtoFile.Descriptor.MessageTypes[10]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public MessageOptions() { + OnConstruction(); + } + + partial void OnConstruction(); + + public MessageOptions(MessageOptions other) : this() { + messageSetWireFormat_ = other.messageSetWireFormat_; + noStandardDescriptorAccessor_ = other.noStandardDescriptorAccessor_; + deprecated_ = other.deprecated_; + mapEntry_ = other.mapEntry_; + uninterpretedOption_ = other.uninterpretedOption_.Clone(); + } + + public MessageOptions Clone() { + return new MessageOptions(this); + } + + public const int MessageSetWireFormatFieldNumber = 1; + private bool messageSetWireFormat_; + public bool MessageSetWireFormat { + get { return messageSetWireFormat_; } + set { + messageSetWireFormat_ = value; + } + } + + public const int NoStandardDescriptorAccessorFieldNumber = 2; + private bool noStandardDescriptorAccessor_; + public bool NoStandardDescriptorAccessor { + get { return noStandardDescriptorAccessor_; } + set { + noStandardDescriptorAccessor_ = value; + } + } + + public const int DeprecatedFieldNumber = 3; + private bool deprecated_; + public bool Deprecated { + get { return deprecated_; } + set { + deprecated_ = value; + } + } + + public const int MapEntryFieldNumber = 7; + private bool mapEntry_; + public bool MapEntry { + get { return mapEntry_; } + set { + mapEntry_ = value; + } + } + + public const int UninterpretedOptionFieldNumber = 999; + private static readonly pb::FieldCodec _repeated_uninterpretedOption_codec + = pb::FieldCodec.ForMessage(7994, global::Google.Protobuf.Reflection.UninterpretedOption.Parser); + private readonly pbc::RepeatedField uninterpretedOption_ = new pbc::RepeatedField(); + public pbc::RepeatedField UninterpretedOption { + get { return uninterpretedOption_; } + } + + public override bool Equals(object other) { + return Equals(other as MessageOptions); + } + + public bool Equals(MessageOptions other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (MessageSetWireFormat != other.MessageSetWireFormat) return false; + if (NoStandardDescriptorAccessor != other.NoStandardDescriptorAccessor) return false; + if (Deprecated != other.Deprecated) return false; + if (MapEntry != other.MapEntry) return false; + if(!uninterpretedOption_.Equals(other.uninterpretedOption_)) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (MessageSetWireFormat != false) hash ^= MessageSetWireFormat.GetHashCode(); + if (NoStandardDescriptorAccessor != false) hash ^= NoStandardDescriptorAccessor.GetHashCode(); + if (Deprecated != false) hash ^= Deprecated.GetHashCode(); + if (MapEntry != false) hash ^= MapEntry.GetHashCode(); + hash ^= uninterpretedOption_.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (MessageSetWireFormat != false) { + output.WriteRawTag(8); + output.WriteBool(MessageSetWireFormat); + } + if (NoStandardDescriptorAccessor != false) { + output.WriteRawTag(16); + output.WriteBool(NoStandardDescriptorAccessor); + } + if (Deprecated != false) { + output.WriteRawTag(24); + output.WriteBool(Deprecated); + } + if (MapEntry != false) { + output.WriteRawTag(56); + output.WriteBool(MapEntry); + } + uninterpretedOption_.WriteTo(output, _repeated_uninterpretedOption_codec); + } + + public int CalculateSize() { + int size = 0; + if (MessageSetWireFormat != false) { + size += 1 + 1; + } + if (NoStandardDescriptorAccessor != false) { + size += 1 + 1; + } + if (Deprecated != false) { + size += 1 + 1; + } + if (MapEntry != false) { + size += 1 + 1; + } + size += uninterpretedOption_.CalculateSize(_repeated_uninterpretedOption_codec); + return size; + } + + public void MergeFrom(MessageOptions other) { + if (other == null) { + return; + } + if (other.MessageSetWireFormat != false) { + MessageSetWireFormat = other.MessageSetWireFormat; + } + if (other.NoStandardDescriptorAccessor != false) { + NoStandardDescriptorAccessor = other.NoStandardDescriptorAccessor; + } + if (other.Deprecated != false) { + Deprecated = other.Deprecated; + } + if (other.MapEntry != false) { + MapEntry = other.MapEntry; + } + uninterpretedOption_.Add(other.uninterpretedOption_); + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 8: { + MessageSetWireFormat = input.ReadBool(); + break; + } + case 16: { + NoStandardDescriptorAccessor = input.ReadBool(); + break; + } + case 24: { + Deprecated = input.ReadBool(); + break; + } + case 56: { + MapEntry = input.ReadBool(); + break; + } + case 7994: { + uninterpretedOption_.AddEntriesFrom(input, _repeated_uninterpretedOption_codec); + break; + } + } + } + } + + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + internal sealed partial class FieldOptions : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new FieldOptions()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorProtoFile.Descriptor.MessageTypes[11]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public FieldOptions() { + OnConstruction(); + } + + partial void OnConstruction(); + + public FieldOptions(FieldOptions other) : this() { + ctype_ = other.ctype_; + packed_ = other.packed_; + jstype_ = other.jstype_; + lazy_ = other.lazy_; + deprecated_ = other.deprecated_; + weak_ = other.weak_; + uninterpretedOption_ = other.uninterpretedOption_.Clone(); + } + + public FieldOptions Clone() { + return new FieldOptions(this); + } + + public const int CtypeFieldNumber = 1; + private global::Google.Protobuf.Reflection.FieldOptions.Types.CType ctype_ = global::Google.Protobuf.Reflection.FieldOptions.Types.CType.STRING; + public global::Google.Protobuf.Reflection.FieldOptions.Types.CType Ctype { + get { return ctype_; } + set { + ctype_ = value; + } + } + + public const int PackedFieldNumber = 2; + private bool packed_; + public bool Packed { + get { return packed_; } + set { + packed_ = value; + } + } + + public const int JstypeFieldNumber = 6; + private global::Google.Protobuf.Reflection.FieldOptions.Types.JSType jstype_ = global::Google.Protobuf.Reflection.FieldOptions.Types.JSType.JS_NORMAL; + public global::Google.Protobuf.Reflection.FieldOptions.Types.JSType Jstype { + get { return jstype_; } + set { + jstype_ = value; + } + } + + public const int LazyFieldNumber = 5; + private bool lazy_; + public bool Lazy { + get { return lazy_; } + set { + lazy_ = value; + } + } + + public const int DeprecatedFieldNumber = 3; + private bool deprecated_; + public bool Deprecated { + get { return deprecated_; } + set { + deprecated_ = value; + } + } + + public const int WeakFieldNumber = 10; + private bool weak_; + public bool Weak { + get { return weak_; } + set { + weak_ = value; + } + } + + public const int UninterpretedOptionFieldNumber = 999; + private static readonly pb::FieldCodec _repeated_uninterpretedOption_codec + = pb::FieldCodec.ForMessage(7994, global::Google.Protobuf.Reflection.UninterpretedOption.Parser); + private readonly pbc::RepeatedField uninterpretedOption_ = new pbc::RepeatedField(); + public pbc::RepeatedField UninterpretedOption { + get { return uninterpretedOption_; } + } + + public override bool Equals(object other) { + return Equals(other as FieldOptions); + } + + public bool Equals(FieldOptions other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Ctype != other.Ctype) return false; + if (Packed != other.Packed) return false; + if (Jstype != other.Jstype) return false; + if (Lazy != other.Lazy) return false; + if (Deprecated != other.Deprecated) return false; + if (Weak != other.Weak) return false; + if(!uninterpretedOption_.Equals(other.uninterpretedOption_)) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (Ctype != global::Google.Protobuf.Reflection.FieldOptions.Types.CType.STRING) hash ^= Ctype.GetHashCode(); + if (Packed != false) hash ^= Packed.GetHashCode(); + if (Jstype != global::Google.Protobuf.Reflection.FieldOptions.Types.JSType.JS_NORMAL) hash ^= Jstype.GetHashCode(); + if (Lazy != false) hash ^= Lazy.GetHashCode(); + if (Deprecated != false) hash ^= Deprecated.GetHashCode(); + if (Weak != false) hash ^= Weak.GetHashCode(); + hash ^= uninterpretedOption_.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (Ctype != global::Google.Protobuf.Reflection.FieldOptions.Types.CType.STRING) { + output.WriteRawTag(8); + output.WriteEnum((int) Ctype); + } + if (Packed != false) { + output.WriteRawTag(16); + output.WriteBool(Packed); + } + if (Deprecated != false) { + output.WriteRawTag(24); + output.WriteBool(Deprecated); + } + if (Lazy != false) { + output.WriteRawTag(40); + output.WriteBool(Lazy); + } + if (Jstype != global::Google.Protobuf.Reflection.FieldOptions.Types.JSType.JS_NORMAL) { + output.WriteRawTag(48); + output.WriteEnum((int) Jstype); + } + if (Weak != false) { + output.WriteRawTag(80); + output.WriteBool(Weak); + } + uninterpretedOption_.WriteTo(output, _repeated_uninterpretedOption_codec); + } + + public int CalculateSize() { + int size = 0; + if (Ctype != global::Google.Protobuf.Reflection.FieldOptions.Types.CType.STRING) { + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Ctype); + } + if (Packed != false) { + size += 1 + 1; + } + if (Jstype != global::Google.Protobuf.Reflection.FieldOptions.Types.JSType.JS_NORMAL) { + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Jstype); + } + if (Lazy != false) { + size += 1 + 1; + } + if (Deprecated != false) { + size += 1 + 1; + } + if (Weak != false) { + size += 1 + 1; + } + size += uninterpretedOption_.CalculateSize(_repeated_uninterpretedOption_codec); + return size; + } + + public void MergeFrom(FieldOptions other) { + if (other == null) { + return; + } + if (other.Ctype != global::Google.Protobuf.Reflection.FieldOptions.Types.CType.STRING) { + Ctype = other.Ctype; + } + if (other.Packed != false) { + Packed = other.Packed; + } + if (other.Jstype != global::Google.Protobuf.Reflection.FieldOptions.Types.JSType.JS_NORMAL) { + Jstype = other.Jstype; + } + if (other.Lazy != false) { + Lazy = other.Lazy; + } + if (other.Deprecated != false) { + Deprecated = other.Deprecated; + } + if (other.Weak != false) { + Weak = other.Weak; + } + uninterpretedOption_.Add(other.uninterpretedOption_); + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 8: { + ctype_ = (global::Google.Protobuf.Reflection.FieldOptions.Types.CType) input.ReadEnum(); + break; + } + case 16: { + Packed = input.ReadBool(); + break; + } + case 24: { + Deprecated = input.ReadBool(); + break; + } + case 40: { + Lazy = input.ReadBool(); + break; + } + case 48: { + jstype_ = (global::Google.Protobuf.Reflection.FieldOptions.Types.JSType) input.ReadEnum(); + break; + } + case 80: { + Weak = input.ReadBool(); + break; + } + case 7994: { + uninterpretedOption_.AddEntriesFrom(input, _repeated_uninterpretedOption_codec); + break; + } + } + } + } + + #region Nested types + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public static partial class Types { + internal enum CType { + STRING = 0, + CORD = 1, + STRING_PIECE = 2, + } + + internal enum JSType { + JS_NORMAL = 0, + JS_STRING = 1, + JS_NUMBER = 2, + } + + } + #endregion + + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + internal sealed partial class EnumOptions : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new EnumOptions()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorProtoFile.Descriptor.MessageTypes[12]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public EnumOptions() { + OnConstruction(); + } + + partial void OnConstruction(); + + public EnumOptions(EnumOptions other) : this() { + allowAlias_ = other.allowAlias_; + deprecated_ = other.deprecated_; + uninterpretedOption_ = other.uninterpretedOption_.Clone(); + } + + public EnumOptions Clone() { + return new EnumOptions(this); + } + + public const int AllowAliasFieldNumber = 2; + private bool allowAlias_; + public bool AllowAlias { + get { return allowAlias_; } + set { + allowAlias_ = value; + } + } + + public const int DeprecatedFieldNumber = 3; + private bool deprecated_; + public bool Deprecated { + get { return deprecated_; } + set { + deprecated_ = value; + } + } + + public const int UninterpretedOptionFieldNumber = 999; + private static readonly pb::FieldCodec _repeated_uninterpretedOption_codec + = pb::FieldCodec.ForMessage(7994, global::Google.Protobuf.Reflection.UninterpretedOption.Parser); + private readonly pbc::RepeatedField uninterpretedOption_ = new pbc::RepeatedField(); + public pbc::RepeatedField UninterpretedOption { + get { return uninterpretedOption_; } + } + + public override bool Equals(object other) { + return Equals(other as EnumOptions); + } + + public bool Equals(EnumOptions other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (AllowAlias != other.AllowAlias) return false; + if (Deprecated != other.Deprecated) return false; + if(!uninterpretedOption_.Equals(other.uninterpretedOption_)) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (AllowAlias != false) hash ^= AllowAlias.GetHashCode(); + if (Deprecated != false) hash ^= Deprecated.GetHashCode(); + hash ^= uninterpretedOption_.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (AllowAlias != false) { + output.WriteRawTag(16); + output.WriteBool(AllowAlias); + } + if (Deprecated != false) { + output.WriteRawTag(24); + output.WriteBool(Deprecated); + } + uninterpretedOption_.WriteTo(output, _repeated_uninterpretedOption_codec); + } + + public int CalculateSize() { + int size = 0; + if (AllowAlias != false) { + size += 1 + 1; + } + if (Deprecated != false) { + size += 1 + 1; + } + size += uninterpretedOption_.CalculateSize(_repeated_uninterpretedOption_codec); + return size; + } + + public void MergeFrom(EnumOptions other) { + if (other == null) { + return; + } + if (other.AllowAlias != false) { + AllowAlias = other.AllowAlias; + } + if (other.Deprecated != false) { + Deprecated = other.Deprecated; + } + uninterpretedOption_.Add(other.uninterpretedOption_); + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 16: { + AllowAlias = input.ReadBool(); + break; + } + case 24: { + Deprecated = input.ReadBool(); + break; + } + case 7994: { + uninterpretedOption_.AddEntriesFrom(input, _repeated_uninterpretedOption_codec); + break; + } + } + } + } + + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + internal sealed partial class EnumValueOptions : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new EnumValueOptions()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorProtoFile.Descriptor.MessageTypes[13]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public EnumValueOptions() { + OnConstruction(); + } + + partial void OnConstruction(); + + public EnumValueOptions(EnumValueOptions other) : this() { + deprecated_ = other.deprecated_; + uninterpretedOption_ = other.uninterpretedOption_.Clone(); + } + + public EnumValueOptions Clone() { + return new EnumValueOptions(this); + } + + public const int DeprecatedFieldNumber = 1; + private bool deprecated_; + public bool Deprecated { + get { return deprecated_; } + set { + deprecated_ = value; + } + } + + public const int UninterpretedOptionFieldNumber = 999; + private static readonly pb::FieldCodec _repeated_uninterpretedOption_codec + = pb::FieldCodec.ForMessage(7994, global::Google.Protobuf.Reflection.UninterpretedOption.Parser); + private readonly pbc::RepeatedField uninterpretedOption_ = new pbc::RepeatedField(); + public pbc::RepeatedField UninterpretedOption { + get { return uninterpretedOption_; } + } + + public override bool Equals(object other) { + return Equals(other as EnumValueOptions); + } + + public bool Equals(EnumValueOptions other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Deprecated != other.Deprecated) return false; + if(!uninterpretedOption_.Equals(other.uninterpretedOption_)) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (Deprecated != false) hash ^= Deprecated.GetHashCode(); + hash ^= uninterpretedOption_.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (Deprecated != false) { + output.WriteRawTag(8); + output.WriteBool(Deprecated); + } + uninterpretedOption_.WriteTo(output, _repeated_uninterpretedOption_codec); + } + + public int CalculateSize() { + int size = 0; + if (Deprecated != false) { + size += 1 + 1; + } + size += uninterpretedOption_.CalculateSize(_repeated_uninterpretedOption_codec); + return size; + } + + public void MergeFrom(EnumValueOptions other) { + if (other == null) { + return; + } + if (other.Deprecated != false) { + Deprecated = other.Deprecated; + } + uninterpretedOption_.Add(other.uninterpretedOption_); + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 8: { + Deprecated = input.ReadBool(); + break; + } + case 7994: { + uninterpretedOption_.AddEntriesFrom(input, _repeated_uninterpretedOption_codec); + break; + } + } + } + } + + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + internal sealed partial class ServiceOptions : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new ServiceOptions()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorProtoFile.Descriptor.MessageTypes[14]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public ServiceOptions() { + OnConstruction(); + } + + partial void OnConstruction(); + + public ServiceOptions(ServiceOptions other) : this() { + deprecated_ = other.deprecated_; + uninterpretedOption_ = other.uninterpretedOption_.Clone(); + } + + public ServiceOptions Clone() { + return new ServiceOptions(this); + } + + public const int DeprecatedFieldNumber = 33; + private bool deprecated_; + public bool Deprecated { + get { return deprecated_; } + set { + deprecated_ = value; + } + } + + public const int UninterpretedOptionFieldNumber = 999; + private static readonly pb::FieldCodec _repeated_uninterpretedOption_codec + = pb::FieldCodec.ForMessage(7994, global::Google.Protobuf.Reflection.UninterpretedOption.Parser); + private readonly pbc::RepeatedField uninterpretedOption_ = new pbc::RepeatedField(); + public pbc::RepeatedField UninterpretedOption { + get { return uninterpretedOption_; } + } + + public override bool Equals(object other) { + return Equals(other as ServiceOptions); + } + + public bool Equals(ServiceOptions other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Deprecated != other.Deprecated) return false; + if(!uninterpretedOption_.Equals(other.uninterpretedOption_)) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (Deprecated != false) hash ^= Deprecated.GetHashCode(); + hash ^= uninterpretedOption_.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (Deprecated != false) { + output.WriteRawTag(136, 2); + output.WriteBool(Deprecated); + } + uninterpretedOption_.WriteTo(output, _repeated_uninterpretedOption_codec); + } + + public int CalculateSize() { + int size = 0; + if (Deprecated != false) { + size += 2 + 1; + } + size += uninterpretedOption_.CalculateSize(_repeated_uninterpretedOption_codec); + return size; + } + + public void MergeFrom(ServiceOptions other) { + if (other == null) { + return; + } + if (other.Deprecated != false) { + Deprecated = other.Deprecated; + } + uninterpretedOption_.Add(other.uninterpretedOption_); + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 264: { + Deprecated = input.ReadBool(); + break; + } + case 7994: { + uninterpretedOption_.AddEntriesFrom(input, _repeated_uninterpretedOption_codec); + break; + } + } + } + } + + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + internal sealed partial class MethodOptions : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new MethodOptions()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorProtoFile.Descriptor.MessageTypes[15]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public MethodOptions() { + OnConstruction(); + } + + partial void OnConstruction(); + + public MethodOptions(MethodOptions other) : this() { + deprecated_ = other.deprecated_; + uninterpretedOption_ = other.uninterpretedOption_.Clone(); + } + + public MethodOptions Clone() { + return new MethodOptions(this); + } + + public const int DeprecatedFieldNumber = 33; + private bool deprecated_; + public bool Deprecated { + get { return deprecated_; } + set { + deprecated_ = value; + } + } + + public const int UninterpretedOptionFieldNumber = 999; + private static readonly pb::FieldCodec _repeated_uninterpretedOption_codec + = pb::FieldCodec.ForMessage(7994, global::Google.Protobuf.Reflection.UninterpretedOption.Parser); + private readonly pbc::RepeatedField uninterpretedOption_ = new pbc::RepeatedField(); + public pbc::RepeatedField UninterpretedOption { + get { return uninterpretedOption_; } + } + + public override bool Equals(object other) { + return Equals(other as MethodOptions); + } + + public bool Equals(MethodOptions other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Deprecated != other.Deprecated) return false; + if(!uninterpretedOption_.Equals(other.uninterpretedOption_)) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (Deprecated != false) hash ^= Deprecated.GetHashCode(); + hash ^= uninterpretedOption_.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (Deprecated != false) { + output.WriteRawTag(136, 2); + output.WriteBool(Deprecated); + } + uninterpretedOption_.WriteTo(output, _repeated_uninterpretedOption_codec); + } + + public int CalculateSize() { + int size = 0; + if (Deprecated != false) { + size += 2 + 1; + } + size += uninterpretedOption_.CalculateSize(_repeated_uninterpretedOption_codec); + return size; + } + + public void MergeFrom(MethodOptions other) { + if (other == null) { + return; + } + if (other.Deprecated != false) { + Deprecated = other.Deprecated; + } + uninterpretedOption_.Add(other.uninterpretedOption_); + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 264: { + Deprecated = input.ReadBool(); + break; + } + case 7994: { + uninterpretedOption_.AddEntriesFrom(input, _repeated_uninterpretedOption_codec); + break; + } + } + } + } + + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + internal sealed partial class UninterpretedOption : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new UninterpretedOption()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorProtoFile.Descriptor.MessageTypes[16]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public UninterpretedOption() { + OnConstruction(); + } + + partial void OnConstruction(); + + public UninterpretedOption(UninterpretedOption other) : this() { + name_ = other.name_.Clone(); + identifierValue_ = other.identifierValue_; + positiveIntValue_ = other.positiveIntValue_; + negativeIntValue_ = other.negativeIntValue_; + doubleValue_ = other.doubleValue_; + stringValue_ = other.stringValue_; + aggregateValue_ = other.aggregateValue_; + } + + public UninterpretedOption Clone() { + return new UninterpretedOption(this); + } + + public const int NameFieldNumber = 2; + private static readonly pb::FieldCodec _repeated_name_codec + = pb::FieldCodec.ForMessage(18, global::Google.Protobuf.Reflection.UninterpretedOption.Types.NamePart.Parser); + private readonly pbc::RepeatedField name_ = new pbc::RepeatedField(); + public pbc::RepeatedField Name { + get { return name_; } + } + + public const int IdentifierValueFieldNumber = 3; + private string identifierValue_ = ""; + public string IdentifierValue { + get { return identifierValue_; } + set { + identifierValue_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int PositiveIntValueFieldNumber = 4; + private ulong positiveIntValue_; + public ulong PositiveIntValue { + get { return positiveIntValue_; } + set { + positiveIntValue_ = value; + } + } + + public const int NegativeIntValueFieldNumber = 5; + private long negativeIntValue_; + public long NegativeIntValue { + get { return negativeIntValue_; } + set { + negativeIntValue_ = value; + } + } + + public const int DoubleValueFieldNumber = 6; + private double doubleValue_; + public double DoubleValue { + get { return doubleValue_; } + set { + doubleValue_ = value; + } + } + + public const int StringValueFieldNumber = 7; + private pb::ByteString stringValue_ = pb::ByteString.Empty; + public pb::ByteString StringValue { + get { return stringValue_; } + set { + stringValue_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int AggregateValueFieldNumber = 8; + private string aggregateValue_ = ""; + public string AggregateValue { + get { return aggregateValue_; } + set { + aggregateValue_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public override bool Equals(object other) { + return Equals(other as UninterpretedOption); + } + + public bool Equals(UninterpretedOption other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if(!name_.Equals(other.name_)) return false; + if (IdentifierValue != other.IdentifierValue) return false; + if (PositiveIntValue != other.PositiveIntValue) return false; + if (NegativeIntValue != other.NegativeIntValue) return false; + if (DoubleValue != other.DoubleValue) return false; + if (StringValue != other.StringValue) return false; + if (AggregateValue != other.AggregateValue) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + hash ^= name_.GetHashCode(); + if (IdentifierValue.Length != 0) hash ^= IdentifierValue.GetHashCode(); + if (PositiveIntValue != 0UL) hash ^= PositiveIntValue.GetHashCode(); + if (NegativeIntValue != 0L) hash ^= NegativeIntValue.GetHashCode(); + if (DoubleValue != 0D) hash ^= DoubleValue.GetHashCode(); + if (StringValue.Length != 0) hash ^= StringValue.GetHashCode(); + if (AggregateValue.Length != 0) hash ^= AggregateValue.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + name_.WriteTo(output, _repeated_name_codec); + if (IdentifierValue.Length != 0) { + output.WriteRawTag(26); + output.WriteString(IdentifierValue); + } + if (PositiveIntValue != 0UL) { + output.WriteRawTag(32); + output.WriteUInt64(PositiveIntValue); + } + if (NegativeIntValue != 0L) { + output.WriteRawTag(40); + output.WriteInt64(NegativeIntValue); + } + if (DoubleValue != 0D) { + output.WriteRawTag(49); + output.WriteDouble(DoubleValue); + } + if (StringValue.Length != 0) { + output.WriteRawTag(58); + output.WriteBytes(StringValue); + } + if (AggregateValue.Length != 0) { + output.WriteRawTag(66); + output.WriteString(AggregateValue); + } + } + + public int CalculateSize() { + int size = 0; + size += name_.CalculateSize(_repeated_name_codec); + if (IdentifierValue.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(IdentifierValue); + } + if (PositiveIntValue != 0UL) { + size += 1 + pb::CodedOutputStream.ComputeUInt64Size(PositiveIntValue); + } + if (NegativeIntValue != 0L) { + size += 1 + pb::CodedOutputStream.ComputeInt64Size(NegativeIntValue); + } + if (DoubleValue != 0D) { + size += 1 + 8; + } + if (StringValue.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeBytesSize(StringValue); + } + if (AggregateValue.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(AggregateValue); + } + return size; + } + + public void MergeFrom(UninterpretedOption other) { + if (other == null) { + return; + } + name_.Add(other.name_); + if (other.IdentifierValue.Length != 0) { + IdentifierValue = other.IdentifierValue; + } + if (other.PositiveIntValue != 0UL) { + PositiveIntValue = other.PositiveIntValue; + } + if (other.NegativeIntValue != 0L) { + NegativeIntValue = other.NegativeIntValue; + } + if (other.DoubleValue != 0D) { + DoubleValue = other.DoubleValue; + } + if (other.StringValue.Length != 0) { + StringValue = other.StringValue; + } + if (other.AggregateValue.Length != 0) { + AggregateValue = other.AggregateValue; + } + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 18: { + name_.AddEntriesFrom(input, _repeated_name_codec); + break; + } + case 26: { + IdentifierValue = input.ReadString(); + break; + } + case 32: { + PositiveIntValue = input.ReadUInt64(); + break; + } + case 40: { + NegativeIntValue = input.ReadInt64(); + break; + } + case 49: { + DoubleValue = input.ReadDouble(); + break; + } + case 58: { + StringValue = input.ReadBytes(); + break; + } + case 66: { + AggregateValue = input.ReadString(); + break; + } + } + } + } + + #region Nested types + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public static partial class Types { + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + internal sealed partial class NamePart : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new NamePart()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.UninterpretedOption.Descriptor.NestedTypes[0]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public NamePart() { + OnConstruction(); + } + + partial void OnConstruction(); + + public NamePart(NamePart other) : this() { + namePart_ = other.namePart_; + isExtension_ = other.isExtension_; + } + + public NamePart Clone() { + return new NamePart(this); + } + + public const int NamePart_FieldNumber = 1; + private string namePart_ = ""; + public string NamePart_ { + get { return namePart_; } + set { + namePart_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int IsExtensionFieldNumber = 2; + private bool isExtension_; + public bool IsExtension { + get { return isExtension_; } + set { + isExtension_ = value; + } + } + + public override bool Equals(object other) { + return Equals(other as NamePart); + } + + public bool Equals(NamePart other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (NamePart_ != other.NamePart_) return false; + if (IsExtension != other.IsExtension) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (NamePart_.Length != 0) hash ^= NamePart_.GetHashCode(); + if (IsExtension != false) hash ^= IsExtension.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (NamePart_.Length != 0) { + output.WriteRawTag(10); + output.WriteString(NamePart_); + } + if (IsExtension != false) { + output.WriteRawTag(16); + output.WriteBool(IsExtension); + } + } + + public int CalculateSize() { + int size = 0; + if (NamePart_.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(NamePart_); + } + if (IsExtension != false) { + size += 1 + 1; + } + return size; + } + + public void MergeFrom(NamePart other) { + if (other == null) { + return; + } + if (other.NamePart_.Length != 0) { + NamePart_ = other.NamePart_; + } + if (other.IsExtension != false) { + IsExtension = other.IsExtension; + } + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 10: { + NamePart_ = input.ReadString(); + break; + } + case 16: { + IsExtension = input.ReadBool(); + break; + } + } + } + } + + } + + } + #endregion + + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + internal sealed partial class SourceCodeInfo : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new SourceCodeInfo()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.DescriptorProtoFile.Descriptor.MessageTypes[17]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public SourceCodeInfo() { + OnConstruction(); + } + + partial void OnConstruction(); + + public SourceCodeInfo(SourceCodeInfo other) : this() { + location_ = other.location_.Clone(); + } + + public SourceCodeInfo Clone() { + return new SourceCodeInfo(this); + } + + public const int LocationFieldNumber = 1; + private static readonly pb::FieldCodec _repeated_location_codec + = pb::FieldCodec.ForMessage(10, global::Google.Protobuf.Reflection.SourceCodeInfo.Types.Location.Parser); + private readonly pbc::RepeatedField location_ = new pbc::RepeatedField(); + public pbc::RepeatedField Location { + get { return location_; } + } + + public override bool Equals(object other) { + return Equals(other as SourceCodeInfo); + } + + public bool Equals(SourceCodeInfo other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if(!location_.Equals(other.location_)) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + hash ^= location_.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + location_.WriteTo(output, _repeated_location_codec); + } + + public int CalculateSize() { + int size = 0; + size += location_.CalculateSize(_repeated_location_codec); + return size; + } + + public void MergeFrom(SourceCodeInfo other) { + if (other == null) { + return; + } + location_.Add(other.location_); + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 10: { + location_.AddEntriesFrom(input, _repeated_location_codec); + break; + } + } + } + } + + #region Nested types + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public static partial class Types { + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + internal sealed partial class Location : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Location()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.Reflection.SourceCodeInfo.Descriptor.NestedTypes[0]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public Location() { + OnConstruction(); + } + + partial void OnConstruction(); + + public Location(Location other) : this() { + path_ = other.path_.Clone(); + span_ = other.span_.Clone(); + leadingComments_ = other.leadingComments_; + trailingComments_ = other.trailingComments_; + leadingDetachedComments_ = other.leadingDetachedComments_.Clone(); + } + + public Location Clone() { + return new Location(this); + } + + public const int PathFieldNumber = 1; + private static readonly pb::FieldCodec _repeated_path_codec + = pb::FieldCodec.ForInt32(10); + private readonly pbc::RepeatedField path_ = new pbc::RepeatedField(); + public pbc::RepeatedField Path { + get { return path_; } + } + + public const int SpanFieldNumber = 2; + private static readonly pb::FieldCodec _repeated_span_codec + = pb::FieldCodec.ForInt32(18); + private readonly pbc::RepeatedField span_ = new pbc::RepeatedField(); + public pbc::RepeatedField Span { + get { return span_; } + } + + public const int LeadingCommentsFieldNumber = 3; + private string leadingComments_ = ""; + public string LeadingComments { + get { return leadingComments_; } + set { + leadingComments_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int TrailingCommentsFieldNumber = 4; + private string trailingComments_ = ""; + public string TrailingComments { + get { return trailingComments_; } + set { + trailingComments_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int LeadingDetachedCommentsFieldNumber = 6; + private static readonly pb::FieldCodec _repeated_leadingDetachedComments_codec + = pb::FieldCodec.ForString(50); + private readonly pbc::RepeatedField leadingDetachedComments_ = new pbc::RepeatedField(); + public pbc::RepeatedField LeadingDetachedComments { + get { return leadingDetachedComments_; } + } + + public override bool Equals(object other) { + return Equals(other as Location); + } + + public bool Equals(Location other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if(!path_.Equals(other.path_)) return false; + if(!span_.Equals(other.span_)) return false; + if (LeadingComments != other.LeadingComments) return false; + if (TrailingComments != other.TrailingComments) return false; + if(!leadingDetachedComments_.Equals(other.leadingDetachedComments_)) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + hash ^= path_.GetHashCode(); + hash ^= span_.GetHashCode(); + if (LeadingComments.Length != 0) hash ^= LeadingComments.GetHashCode(); + if (TrailingComments.Length != 0) hash ^= TrailingComments.GetHashCode(); + hash ^= leadingDetachedComments_.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + path_.WriteTo(output, _repeated_path_codec); + span_.WriteTo(output, _repeated_span_codec); + if (LeadingComments.Length != 0) { + output.WriteRawTag(26); + output.WriteString(LeadingComments); + } + if (TrailingComments.Length != 0) { + output.WriteRawTag(34); + output.WriteString(TrailingComments); + } + leadingDetachedComments_.WriteTo(output, _repeated_leadingDetachedComments_codec); + } + + public int CalculateSize() { + int size = 0; + size += path_.CalculateSize(_repeated_path_codec); + size += span_.CalculateSize(_repeated_span_codec); + if (LeadingComments.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(LeadingComments); + } + if (TrailingComments.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(TrailingComments); + } + size += leadingDetachedComments_.CalculateSize(_repeated_leadingDetachedComments_codec); + return size; + } + + public void MergeFrom(Location other) { + if (other == null) { + return; + } + path_.Add(other.path_); + span_.Add(other.span_); + if (other.LeadingComments.Length != 0) { + LeadingComments = other.LeadingComments; + } + if (other.TrailingComments.Length != 0) { + TrailingComments = other.TrailingComments; + } + leadingDetachedComments_.Add(other.leadingDetachedComments_); + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 10: + case 8: { + path_.AddEntriesFrom(input, _repeated_path_codec); + break; + } + case 18: + case 16: { + span_.AddEntriesFrom(input, _repeated_span_codec); + break; + } + case 26: { + LeadingComments = input.ReadString(); + break; + } + case 34: { + TrailingComments = input.ReadString(); + break; + } + case 50: { + leadingDetachedComments_.AddEntriesFrom(input, _repeated_leadingDetachedComments_codec); + break; + } + } + } + } + + } + + } + #endregion + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/src/ProtocolBuffers/Descriptors/DescriptorUtil.cs b/csharp/src/Google.Protobuf/Reflection/DescriptorUtil.cs similarity index 81% rename from csharp/src/ProtocolBuffers/Descriptors/DescriptorUtil.cs rename to csharp/src/Google.Protobuf/Reflection/DescriptorUtil.cs index 00efdbe86443d..f5570fc40a24f 100644 --- a/csharp/src/ProtocolBuffers/Descriptors/DescriptorUtil.cs +++ b/csharp/src/Google.Protobuf/Reflection/DescriptorUtil.cs @@ -1,64 +1,64 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -using System.Collections.Generic; -using Google.ProtocolBuffers.Collections; - -namespace Google.ProtocolBuffers.Descriptors -{ - /// - /// Internal class containing utility methods when working with descriptors. - /// - internal static class DescriptorUtil - { - /// - /// Equivalent to Func[TInput, int, TOutput] but usable in .NET 2.0. Only used to convert - /// arrays. - /// - internal delegate TOutput IndexedConverter(TInput element, int index); - - /// - /// Converts the given array into a read-only list, applying the specified conversion to - /// each input element. - /// - internal static IList ConvertAndMakeReadOnly(IList input, - IndexedConverter - converter) - { - TOutput[] array = new TOutput[input.Count]; - for (int i = 0; i < array.Length; i++) - { - array[i] = converter(input[i], i); - } - return Lists.AsReadOnly(array); - } - } +#region Copyright notice and license +// 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. +#endregion + +using System.Collections.Generic; +using System.Collections.ObjectModel; + +namespace Google.Protobuf.Reflection +{ + /// + /// Internal class containing utility methods when working with descriptors. + /// + internal static class DescriptorUtil + { + /// + /// Equivalent to Func[TInput, int, TOutput] but usable in .NET 2.0. Only used to convert + /// arrays. + /// + internal delegate TOutput IndexedConverter(TInput element, int index); + + /// + /// Converts the given array into a read-only list, applying the specified conversion to + /// each input element. + /// + internal static IList ConvertAndMakeReadOnly + (IList input, IndexedConverter converter) + { + TOutput[] array = new TOutput[input.Count]; + for (int i = 0; i < array.Length; i++) + { + array[i] = converter(input[i], i); + } + return new ReadOnlyCollection(array); + } + } } \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers/Descriptors/DescriptorValidationException.cs b/csharp/src/Google.Protobuf/Reflection/DescriptorValidationException.cs similarity index 84% rename from csharp/src/ProtocolBuffers/Descriptors/DescriptorValidationException.cs rename to csharp/src/Google.Protobuf/Reflection/DescriptorValidationException.cs index d05d60d753407..143671dbd4447 100644 --- a/csharp/src/ProtocolBuffers/Descriptors/DescriptorValidationException.cs +++ b/csharp/src/Google.Protobuf/Reflection/DescriptorValidationException.cs @@ -1,90 +1,80 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -using System; - -namespace Google.ProtocolBuffers.Descriptors -{ - /// - /// Thrown when building descriptors fails because the source DescriptorProtos - /// are not valid. - /// - public sealed class DescriptorValidationException : Exception - { - private readonly String name; - private readonly IMessage proto; - private readonly string description; - - /// - /// The full name of the descriptor where the error occurred. - /// - public String ProblemSymbolName - { - get { return name; } - } - - /// - /// The protocol message representation of the invalid descriptor. - /// - public IMessage ProblemProto - { - get { return proto; } - } - - /// - /// A human-readable description of the error. (The Message property - /// is made up of the descriptor's name and this description.) - /// - public string Description - { - get { return description; } - } - - internal DescriptorValidationException(IDescriptor problemDescriptor, string description) : - base(problemDescriptor.FullName + ": " + description) - { - // Note that problemDescriptor may be partially uninitialized, so we - // don't want to expose it directly to the user. So, we only provide - // the name and the original proto. - name = problemDescriptor.FullName; - proto = problemDescriptor.Proto; - this.description = description; - } - - internal DescriptorValidationException(IDescriptor problemDescriptor, string description, Exception cause) : - base(problemDescriptor.FullName + ": " + description, cause) - { - name = problemDescriptor.FullName; - proto = problemDescriptor.Proto; - this.description = description; - } - } +#region Copyright notice and license +// 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. +#endregion + +using System; + +namespace Google.Protobuf.Reflection +{ + /// + /// Thrown when building descriptors fails because the source DescriptorProtos + /// are not valid. + /// + public sealed class DescriptorValidationException : Exception + { + private readonly String name; + private readonly string description; + + /// + /// The full name of the descriptor where the error occurred. + /// + public String ProblemSymbolName + { + get { return name; } + } + + /// + /// A human-readable description of the error. (The Message property + /// is made up of the descriptor's name and this description.) + /// + public string Description + { + get { return description; } + } + + internal DescriptorValidationException(IDescriptor problemDescriptor, string description) : + base(problemDescriptor.FullName + ": " + description) + { + // Note that problemDescriptor may be partially uninitialized, so we + // don't want to expose it directly to the user. So, we only provide + // the name and the original proto. + name = problemDescriptor.FullName; + this.description = description; + } + + internal DescriptorValidationException(IDescriptor problemDescriptor, string description, Exception cause) : + base(problemDescriptor.FullName + ": " + description, cause) + { + name = problemDescriptor.FullName; + this.description = description; + } + } } \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers/Descriptors/EnumDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/EnumDescriptor.cs similarity index 72% rename from csharp/src/ProtocolBuffers/Descriptors/EnumDescriptor.cs rename to csharp/src/Google.Protobuf/Reflection/EnumDescriptor.cs index a0b81b6917614..285f26f38aaef 100644 --- a/csharp/src/ProtocolBuffers/Descriptors/EnumDescriptor.cs +++ b/csharp/src/Google.Protobuf/Reflection/EnumDescriptor.cs @@ -1,126 +1,116 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -using System.Collections.Generic; -using Google.ProtocolBuffers.DescriptorProtos; - -namespace Google.ProtocolBuffers.Descriptors -{ - /// - /// Descriptor for an enum type in a .proto file. - /// - public sealed class EnumDescriptor : IndexedDescriptorBase, - IEnumLiteMap - { - private readonly MessageDescriptor containingType; - private readonly IList values; - - internal EnumDescriptor(EnumDescriptorProto proto, FileDescriptor file, MessageDescriptor parent, int index) - : base(proto, file, ComputeFullName(file, parent, proto.Name), index) - { - containingType = parent; - - if (proto.ValueCount == 0) - { - // We cannot allow enums with no values because this would mean there - // would be no valid default value for fields of this type. - throw new DescriptorValidationException(this, "Enums must contain at least one value."); - } - - values = DescriptorUtil.ConvertAndMakeReadOnly(proto.ValueList, - (value, i) => new EnumValueDescriptor(value, file, this, i)); - - File.DescriptorPool.AddSymbol(this); - } - - /// - /// If this is a nested type, get the outer descriptor, otherwise null. - /// - public MessageDescriptor ContainingType - { - get { return containingType; } - } - - /// - /// An unmodifiable list of defined value descriptors for this enum. - /// - public IList Values - { - get { return values; } - } - - /// - /// Logic moved from FieldSet to continue current behavior - /// - public bool IsValidValue(IEnumLite value) - { - return value is EnumValueDescriptor && ((EnumValueDescriptor) value).EnumDescriptor == this; - } - - /// - /// Finds an enum value by number. If multiple enum values have the - /// same number, this returns the first defined value with that number. - /// - public EnumValueDescriptor FindValueByNumber(int number) - { - return File.DescriptorPool.FindEnumValueByNumber(this, number); - } - - IEnumLite IEnumLiteMap.FindValueByNumber(int number) - { - return FindValueByNumber(number); - } - - IEnumLite IEnumLiteMap.FindValueByName(string name) - { - return FindValueByName(name); - } - - /// - /// Finds an enum value by name. - /// - /// The unqualified name of the value (e.g. "FOO"). - /// The value's descriptor, or null if not found. - public EnumValueDescriptor FindValueByName(string name) - { - return File.DescriptorPool.FindSymbol(FullName + "." + name); - } - - internal override void ReplaceProto(EnumDescriptorProto newProto) - { - base.ReplaceProto(newProto); - for (int i = 0; i < values.Count; i++) - { - values[i].ReplaceProto(newProto.GetValue(i)); - } - } - } +#region Copyright notice and license +// 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. +#endregion + +using System; +using System.Collections.Generic; + +namespace Google.Protobuf.Reflection +{ + /// + /// Descriptor for an enum type in a .proto file. + /// + public sealed class EnumDescriptor : DescriptorBase + { + private readonly EnumDescriptorProto proto; + private readonly MessageDescriptor containingType; + private readonly IList values; + private readonly Type generatedType; + + internal EnumDescriptor(EnumDescriptorProto proto, FileDescriptor file, MessageDescriptor parent, int index, Type generatedType) + : base(file, file.ComputeFullName(parent, proto.Name), index) + { + this.proto = proto; + this.generatedType = generatedType; + containingType = parent; + + if (proto.Value.Count == 0) + { + // We cannot allow enums with no values because this would mean there + // would be no valid default value for fields of this type. + throw new DescriptorValidationException(this, "Enums must contain at least one value."); + } + + values = DescriptorUtil.ConvertAndMakeReadOnly(proto.Value, + (value, i) => new EnumValueDescriptor(value, file, this, i)); + + File.DescriptorPool.AddSymbol(this); + } + + internal EnumDescriptorProto Proto { get { return proto; } } + + /// + /// The brief name of the descriptor's target. + /// + public override string Name { get { return proto.Name; } } + + /// + /// The generated type for this enum, or null if the descriptor does not represent a generated type. + /// + public Type GeneratedType { get { return generatedType; } } + + /// + /// If this is a nested type, get the outer descriptor, otherwise null. + /// + public MessageDescriptor ContainingType + { + get { return containingType; } + } + + /// + /// An unmodifiable list of defined value descriptors for this enum. + /// + public IList Values + { + get { return values; } + } + + /// + /// Finds an enum value by number. If multiple enum values have the + /// same number, this returns the first defined value with that number. + /// If there is no value for the given number, this returns null. + /// + public EnumValueDescriptor FindValueByNumber(int number) + { + return File.DescriptorPool.FindEnumValueByNumber(this, number); + } + + /// + /// Finds an enum value by name. + /// + /// The unqualified name of the value (e.g. "FOO"). + /// The value's descriptor, or null if not found. + public EnumValueDescriptor FindValueByName(string name) + { + return File.DescriptorPool.FindSymbol(FullName + "." + name); + } + } } \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers/Descriptors/EnumValueDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/EnumValueDescriptor.cs similarity index 67% rename from csharp/src/ProtocolBuffers/Descriptors/EnumValueDescriptor.cs rename to csharp/src/Google.Protobuf/Reflection/EnumValueDescriptor.cs index afb9cbbc3f8d4..b212ce961854a 100644 --- a/csharp/src/ProtocolBuffers/Descriptors/EnumValueDescriptor.cs +++ b/csharp/src/Google.Protobuf/Reflection/EnumValueDescriptor.cs @@ -1,63 +1,70 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -using Google.ProtocolBuffers.DescriptorProtos; - -namespace Google.ProtocolBuffers.Descriptors -{ - /// - /// Descriptor for a single enum value within an enum in a .proto file. - /// - public sealed class EnumValueDescriptor : IndexedDescriptorBase, - IEnumLite - { - private readonly EnumDescriptor enumDescriptor; - - internal EnumValueDescriptor(EnumValueDescriptorProto proto, FileDescriptor file, - EnumDescriptor parent, int index) - : base(proto, file, parent.FullName + "." + proto.Name, index) - { - enumDescriptor = parent; - file.DescriptorPool.AddSymbol(this); - file.DescriptorPool.AddEnumValueByNumber(this); - } - - public int Number - { - get { return Proto.Number; } - } - - public EnumDescriptor EnumDescriptor - { - get { return enumDescriptor; } - } - } +#region Copyright notice and license +// 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. +#endregion + +namespace Google.Protobuf.Reflection +{ + /// + /// Descriptor for a single enum value within an enum in a .proto file. + /// + public sealed class EnumValueDescriptor : DescriptorBase + { + private readonly EnumDescriptor enumDescriptor; + private readonly EnumValueDescriptorProto proto; + + internal EnumValueDescriptor(EnumValueDescriptorProto proto, FileDescriptor file, + EnumDescriptor parent, int index) + : base(file, parent.FullName + "." + proto.Name, index) + { + this.proto = proto; + enumDescriptor = parent; + file.DescriptorPool.AddSymbol(this); + file.DescriptorPool.AddEnumValueByNumber(this); + } + + internal EnumValueDescriptorProto Proto { get { return proto; } } + + /// + /// Returns the name of the enum value described by this object. + /// + public override string Name { get { return proto.Name; } } + + /// + /// Returns the number associated with this enum value. + /// + public int Number { get { return Proto.Number; } } + + /// + /// Returns the enum descriptor that this value is part of. + /// + public EnumDescriptor EnumDescriptor { get { return enumDescriptor; } } + } } \ No newline at end of file diff --git a/csharp/src/Google.Protobuf/Reflection/FieldAccessorBase.cs b/csharp/src/Google.Protobuf/Reflection/FieldAccessorBase.cs new file mode 100644 index 0000000000000..82ce50518d8e9 --- /dev/null +++ b/csharp/src/Google.Protobuf/Reflection/FieldAccessorBase.cs @@ -0,0 +1,63 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using System; +using System.Reflection; +using Google.Protobuf.Compatibility; + +namespace Google.Protobuf.Reflection +{ + /// + /// Base class for field accessors. + /// + internal abstract class FieldAccessorBase : IFieldAccessor + { + private readonly Func getValueDelegate; + private readonly FieldDescriptor descriptor; + + internal FieldAccessorBase(PropertyInfo property, FieldDescriptor descriptor) + { + this.descriptor = descriptor; + getValueDelegate = ReflectionUtil.CreateFuncIMessageObject(property.GetGetMethod()); + } + + public FieldDescriptor Descriptor { get { return descriptor; } } + + public object GetValue(IMessage message) + { + return getValueDelegate(message); + } + + public abstract void Clear(IMessage message); + public abstract void SetValue(IMessage message, object value); + } +} diff --git a/csharp/src/Google.Protobuf/Reflection/FieldDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/FieldDescriptor.cs new file mode 100644 index 0000000000000..901cbf47a55b2 --- /dev/null +++ b/csharp/src/Google.Protobuf/Reflection/FieldDescriptor.cs @@ -0,0 +1,350 @@ +#region Copyright notice and license +// 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. +#endregion + +using System; +using System.Linq; +using Google.Protobuf.Compatibility; + +namespace Google.Protobuf.Reflection +{ + /// + /// Descriptor for a field or extension within a message in a .proto file. + /// + public sealed class FieldDescriptor : DescriptorBase, IComparable + { + private readonly FieldDescriptorProto proto; + private EnumDescriptor enumType; + private MessageDescriptor messageType; + private readonly MessageDescriptor containingType; + private readonly OneofDescriptor containingOneof; + private FieldType fieldType; + private readonly string propertyName; // Annoyingly, needed in Crosslink. + private IFieldAccessor accessor; + + internal FieldDescriptor(FieldDescriptorProto proto, FileDescriptor file, + MessageDescriptor parent, int index, string propertyName) + : base(file, file.ComputeFullName(parent, proto.Name), index) + { + this.proto = proto; + if (proto.Type != 0) + { + fieldType = GetFieldTypeFromProtoType(proto.Type); + } + + if (FieldNumber <= 0) + { + throw new DescriptorValidationException(this, + "Field numbers must be positive integers."); + } + containingType = parent; + // OneofIndex "defaults" to -1 due to a hack in FieldDescriptor.OnConstruction. + if (proto.OneofIndex != -1) + { + if (proto.OneofIndex < 0 || proto.OneofIndex >= parent.Proto.OneofDecl.Count) + { + throw new DescriptorValidationException(this, + "FieldDescriptorProto.oneof_index is out of range for type " + parent.Name); + } + containingOneof = parent.Oneofs[proto.OneofIndex]; + } + + file.DescriptorPool.AddSymbol(this); + // We can't create the accessor until we've cross-linked, unfortunately, as we + // may not know whether the type of the field is a map or not. Remember the property name + // for later. + // We could trust the generated code and check whether the type of the property is + // a MapField, but that feels a tad nasty. + this.propertyName = propertyName; + } + + /// + /// The brief name of the descriptor's target. + /// + public override string Name { get { return proto.Name; } } + + internal FieldDescriptorProto Proto { get { return proto; } } + + /// + /// Returns the accessor for this field, or null if this descriptor does + /// not support reflective access. + /// + /// + /// While a describes the field, it does not provide + /// any way of obtaining or changing the value of the field within a specific message; + /// that is the responsibility of the accessor. + /// + public IFieldAccessor Accessor { get { return accessor; } } + + /// + /// Maps a field type as included in the .proto file to a FieldType. + /// + private static FieldType GetFieldTypeFromProtoType(FieldDescriptorProto.Types.Type type) + { + switch (type) + { + case FieldDescriptorProto.Types.Type.TYPE_DOUBLE: + return FieldType.Double; + case FieldDescriptorProto.Types.Type.TYPE_FLOAT: + return FieldType.Float; + case FieldDescriptorProto.Types.Type.TYPE_INT64: + return FieldType.Int64; + case FieldDescriptorProto.Types.Type.TYPE_UINT64: + return FieldType.UInt64; + case FieldDescriptorProto.Types.Type.TYPE_INT32: + return FieldType.Int32; + case FieldDescriptorProto.Types.Type.TYPE_FIXED64: + return FieldType.Fixed64; + case FieldDescriptorProto.Types.Type.TYPE_FIXED32: + return FieldType.Fixed32; + case FieldDescriptorProto.Types.Type.TYPE_BOOL: + return FieldType.Bool; + case FieldDescriptorProto.Types.Type.TYPE_STRING: + return FieldType.String; + case FieldDescriptorProto.Types.Type.TYPE_GROUP: + return FieldType.Group; + case FieldDescriptorProto.Types.Type.TYPE_MESSAGE: + return FieldType.Message; + case FieldDescriptorProto.Types.Type.TYPE_BYTES: + return FieldType.Bytes; + case FieldDescriptorProto.Types.Type.TYPE_UINT32: + return FieldType.UInt32; + case FieldDescriptorProto.Types.Type.TYPE_ENUM: + return FieldType.Enum; + case FieldDescriptorProto.Types.Type.TYPE_SFIXED32: + return FieldType.SFixed32; + case FieldDescriptorProto.Types.Type.TYPE_SFIXED64: + return FieldType.SFixed64; + case FieldDescriptorProto.Types.Type.TYPE_SINT32: + return FieldType.SInt32; + case FieldDescriptorProto.Types.Type.TYPE_SINT64: + return FieldType.SInt64; + default: + throw new ArgumentException("Invalid type specified"); + } + } + + /// + /// Returns true if this field is a repeated field; false otherwise. + /// + public bool IsRepeated + { + get { return Proto.Label == FieldDescriptorProto.Types.Label.LABEL_REPEATED; } + } + + /// + /// Returns true if this field is a map field; false otherwise. + /// + public bool IsMap + { + get { return fieldType == FieldType.Message && messageType.Proto.Options != null && messageType.Proto.Options.MapEntry; } + } + + /// + /// Returns true if this field is a packed, repeated field; false otherwise. + /// + public bool IsPacked + { + // Note the || rather than && here - we're effectively defaulting to packed, because that *is* + // the default in proto3, which is all we support. We may give the wrong result for the protos + // within descriptor.proto, but that's okay, as they're never exposed and we don't use IsPacked + // within the runtime. + get { return Proto.Options == null || Proto.Options.Packed; } + } + + /// + /// Get the field's containing message type. + /// + public MessageDescriptor ContainingType + { + get { return containingType; } + } + + /// + /// Returns the oneof containing this field, or null if it is not part of a oneof. + /// + public OneofDescriptor ContainingOneof + { + get { return containingOneof; } + } + + /// + /// Returns the type of the field. + /// + public FieldType FieldType + { + get { return fieldType; } + } + + /// + /// Returns the field number declared in the proto file. + /// + public int FieldNumber + { + get { return Proto.Number; } + } + + /// + /// Compares this descriptor with another one, ordering in "canonical" order + /// which simply means ascending order by field number. + /// must be a field of the same type, i.e. the of + /// both fields must be the same. + /// + public int CompareTo(FieldDescriptor other) + { + if (other.containingType != containingType) + { + throw new ArgumentException("FieldDescriptors can only be compared to other FieldDescriptors " + + "for fields of the same message type."); + } + return FieldNumber - other.FieldNumber; + } + + /// + /// For enum fields, returns the field's type. + /// + public EnumDescriptor EnumType + { + get + { + if (fieldType != FieldType.Enum) + { + throw new InvalidOperationException("EnumType is only valid for enum fields."); + } + return enumType; + } + } + + /// + /// For embedded message and group fields, returns the field's type. + /// + public MessageDescriptor MessageType + { + get + { + if (fieldType != FieldType.Message) + { + throw new InvalidOperationException("MessageType is only valid for enum fields."); + } + return messageType; + } + } + + /// + /// Look up and cross-link all field types etc. + /// + internal void CrossLink() + { + if (Proto.TypeName != "") + { + IDescriptor typeDescriptor = + File.DescriptorPool.LookupSymbol(Proto.TypeName, this); + + if (Proto.Type != 0) + { + // Choose field type based on symbol. + if (typeDescriptor is MessageDescriptor) + { + fieldType = FieldType.Message; + } + else if (typeDescriptor is EnumDescriptor) + { + fieldType = FieldType.Enum; + } + else + { + throw new DescriptorValidationException(this, "\"" + Proto.TypeName + "\" is not a type."); + } + } + + if (fieldType == FieldType.Message) + { + if (!(typeDescriptor is MessageDescriptor)) + { + throw new DescriptorValidationException(this, + "\"" + Proto.TypeName + "\" is not a message type."); + } + messageType = (MessageDescriptor) typeDescriptor; + + if (Proto.DefaultValue != "") + { + throw new DescriptorValidationException(this, "Messages can't have default values."); + } + } + else if (fieldType == FieldType.Enum) + { + if (!(typeDescriptor is EnumDescriptor)) + { + throw new DescriptorValidationException(this, "\"" + Proto.TypeName + "\" is not an enum type."); + } + enumType = (EnumDescriptor) typeDescriptor; + } + else + { + throw new DescriptorValidationException(this, "Field with primitive type has type_name."); + } + } + else + { + if (fieldType == FieldType.Message || fieldType == FieldType.Enum) + { + throw new DescriptorValidationException(this, "Field with message or enum type missing type_name."); + } + } + + // Note: no attempt to perform any default value parsing + + File.DescriptorPool.AddFieldByNumber(this); + + if (containingType != null && containingType.Proto.Options != null && containingType.Proto.Options.MessageSetWireFormat) + { + throw new DescriptorValidationException(this, "MessageSet format is not supported."); + } + accessor = CreateAccessor(propertyName); + } + + private IFieldAccessor CreateAccessor(string propertyName) + { + if (containingType.GeneratedType == null || propertyName == null) + { + return null; + } + var property = containingType.GeneratedType.GetProperty(propertyName); + if (property == null) + { + throw new DescriptorValidationException(this, "Property " + propertyName + " not found in " + containingType.GeneratedType); + } + return IsMap ? new MapFieldAccessor(property, this) + : IsRepeated ? new RepeatedFieldAccessor(property, this) + : (IFieldAccessor) new SingleFieldAccessor(property, this); + } + } +} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers/FieldAccess/IFieldAccessor.cs b/csharp/src/Google.Protobuf/Reflection/FieldType.cs similarity index 53% rename from csharp/src/ProtocolBuffers/FieldAccess/IFieldAccessor.cs rename to csharp/src/Google.Protobuf/Reflection/FieldType.cs index 39d3b85b81c08..1658e34cd1e16 100644 --- a/csharp/src/ProtocolBuffers/FieldAccess/IFieldAccessor.cs +++ b/csharp/src/Google.Protobuf/Reflection/FieldType.cs @@ -1,95 +1,113 @@ -// 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. - -namespace Google.ProtocolBuffers.FieldAccess -{ - /// - /// Allows fields to be reflectively accessed in a smart manner. - /// The property descriptors for each field are created once and then cached. - /// In addition, this interface holds knowledge of repeated fields, builders etc. - /// - internal interface IFieldAccessor - where TMessage : IMessage - where TBuilder : IBuilder - { - /// - /// Indicates whether the specified message contains the field. - /// - bool Has(TMessage message); - - /// - /// Gets the count of the repeated field in the specified message. - /// - int GetRepeatedCount(TMessage message); - - /// - /// Clears the field in the specified builder. - /// - /// - void Clear(TBuilder builder); - - /// - /// Creates a builder for the type of this field (which must be a message field). - /// - IBuilder CreateBuilder(); - - /// - /// Accessor for single fields - /// - object GetValue(TMessage message); - - /// - /// Mutator for single fields - /// - void SetValue(TBuilder builder, object value); - - /// - /// Accessor for repeated fields - /// - object GetRepeatedValue(TMessage message, int index); - - /// - /// Mutator for repeated fields - /// - void SetRepeated(TBuilder builder, int index, object value); - - /// - /// Adds the specified value to the field in the given builder. - /// - void AddRepeated(TBuilder builder, object value); - - /// - /// Returns a read-only wrapper around the value of a repeated field. - /// - object GetRepeatedWrapper(TBuilder builder); - } +#region Copyright notice and license +// 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. +#endregion + +namespace Google.Protobuf.Reflection +{ + /// + /// Enumeration of all the possible field types. + /// + public enum FieldType + { + /// + /// The double field type. + /// + Double, + /// + /// The float field type. + /// + Float, + /// + /// The int64 field type. + /// + Int64, + /// + /// The uint64 field type. + /// + UInt64, + /// + /// The int32 field type. + /// + Int32, + /// + /// The fixed64 field type. + /// + Fixed64, + /// + /// The fixed32 field type. + /// + Fixed32, + /// + /// The bool field type. + /// + Bool, + /// + /// The string field type. + /// + String, + /// + /// The field type used for groups (not supported in this implementation). + /// + Group, + /// + /// The field type used for message fields. + /// + Message, + /// + /// The bytes field type. + /// + Bytes, + /// + /// The uint32 field type. + /// + UInt32, + /// + /// The sfixed32 field type. + /// + SFixed32, + /// + /// The sfixed64 field type. + /// + SFixed64, + /// + /// The sint32 field type. + /// + SInt32, + /// + /// The sint64 field type. + /// + SInt64, + /// + /// The field type used for enum fields. + /// + Enum + } } \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers/Descriptors/FileDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/FileDescriptor.cs similarity index 57% rename from csharp/src/ProtocolBuffers/Descriptors/FileDescriptor.cs rename to csharp/src/Google.Protobuf/Reflection/FileDescriptor.cs index fed032bff5693..bad58faa9f662 100644 --- a/csharp/src/ProtocolBuffers/Descriptors/FileDescriptor.cs +++ b/csharp/src/Google.Protobuf/Reflection/FileDescriptor.cs @@ -1,476 +1,387 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.IO; -using Google.ProtocolBuffers.DescriptorProtos; -using FileOptions = Google.ProtocolBuffers.DescriptorProtos.FileOptions; - -namespace Google.ProtocolBuffers.Descriptors -{ - /// - /// Describes a .proto file, including everything defined within. - /// IDescriptor is implemented such that the File property returns this descriptor, - /// and the FullName is the same as the Name. - /// - public sealed class FileDescriptor : IDescriptor - { - private FileDescriptorProto proto; - private readonly IList messageTypes; - private readonly IList enumTypes; - private readonly IList services; - private readonly IList extensions; - private readonly IList dependencies; - private readonly IList publicDependencies; - private readonly DescriptorPool pool; - - public enum ProtoSyntax - { - Proto2, - Proto3 - } - - public ProtoSyntax Syntax - { - get { return proto.Syntax == "proto3" ? ProtoSyntax.Proto3 : ProtoSyntax.Proto2; } - } - - private FileDescriptor(FileDescriptorProto proto, FileDescriptor[] dependencies, DescriptorPool pool, bool allowUnknownDependencies) - { - this.pool = pool; - this.proto = proto; - this.dependencies = new ReadOnlyCollection((FileDescriptor[]) dependencies.Clone()); - - publicDependencies = DeterminePublicDependencies(this, proto, dependencies, allowUnknownDependencies); - - pool.AddPackage(Package, this); - - messageTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.MessageTypeList, - (message, index) => - new MessageDescriptor(message, this, null, index)); - - enumTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.EnumTypeList, - (enumType, index) => - new EnumDescriptor(enumType, this, null, index)); - - services = DescriptorUtil.ConvertAndMakeReadOnly(proto.ServiceList, - (service, index) => - new ServiceDescriptor(service, this, index)); - - extensions = DescriptorUtil.ConvertAndMakeReadOnly(proto.ExtensionList, - (field, index) => - new FieldDescriptor(field, this, null, index, true)); - } - - /// - /// Extracts public dependencies from direct dependencies. This is a static method despite its - /// first parameter, as the value we're in the middle of constructing is only used for exceptions. - /// - private static IList DeterminePublicDependencies(FileDescriptor @this, FileDescriptorProto proto, FileDescriptor[] dependencies, bool allowUnknownDependencies) - { - var nameToFileMap = new Dictionary(); - foreach (var file in dependencies) - { - nameToFileMap[file.Name] = file; - } - var publicDependencies = new List(); - for (int i = 0; i < proto.PublicDependencyCount; i++) - { - int index = proto.PublicDependencyList[i]; - if (index < 0 || index >= proto.DependencyCount) - { - throw new DescriptorValidationException(@this, "Invalid public dependency index."); - } - string name = proto.DependencyList[index]; - FileDescriptor file = nameToFileMap[name]; - if (file == null) - { - if (!allowUnknownDependencies) - { - throw new DescriptorValidationException(@this, "Invalid public dependency: " + name); - } - // Ignore unknown dependencies. - } - else - { - publicDependencies.Add(file); - } - } - return new ReadOnlyCollection(publicDependencies); - } - - - static readonly char[] PathSeperators = new char[] { '/', '\\' }; - - /// - /// The descriptor in its protocol message representation. - /// - public FileDescriptorProto Proto - { - get { return proto; } - } - - /// - /// The defined in descriptor.proto. - /// - public FileOptions Options - { - get { return proto.Options; } - } - - /// - /// The file name. - /// - public string Name - { - get { return proto.Name; } - } - - /// - /// The package as declared in the .proto file. This may or may not - /// be equivalent to the .NET namespace of the generated classes. - /// - public string Package - { - get { return proto.Package; } - } - - /// - /// Unmodifiable list of top-level message types declared in this file. - /// - public IList MessageTypes - { - get { return messageTypes; } - } - - /// - /// Unmodifiable list of top-level enum types declared in this file. - /// - public IList EnumTypes - { - get { return enumTypes; } - } - - /// - /// Unmodifiable list of top-level services declared in this file. - /// - public IList Services - { - get { return services; } - } - - /// - /// Unmodifiable list of top-level extensions declared in this file. - /// - public IList Extensions - { - get { return extensions; } - } - - /// - /// Unmodifiable list of this file's dependencies (imports). - /// - public IList Dependencies - { - get { return dependencies; } - } - - /// - /// Unmodifiable list of this file's public dependencies (public imports). - /// - public IList PublicDependencies - { - get { return publicDependencies; } - } - - /// - /// Implementation of IDescriptor.FullName - just returns the same as Name. - /// - string IDescriptor.FullName - { - get { return Name; } - } - - /// - /// Implementation of IDescriptor.File - just returns this descriptor. - /// - FileDescriptor IDescriptor.File - { - get { return this; } - } - - /// - /// Protocol buffer describing this descriptor. - /// - IMessage IDescriptor.Proto - { - get { return Proto; } - } - - /// - /// Pool containing symbol descriptors. - /// - internal DescriptorPool DescriptorPool - { - get { return pool; } - } - - /// - /// Finds a type (message, enum, service or extension) in the file by name. Does not find nested types. - /// - /// The unqualified type name to look for. - /// The type of descriptor to look for (or ITypeDescriptor for any) - /// The type's descriptor, or null if not found. - public T FindTypeByName(String name) - where T : class, IDescriptor - { - // Don't allow looking up nested types. This will make optimization - // easier later. - if (name.IndexOf('.') != -1) - { - return null; - } - if (Package.Length > 0) - { - name = Package + "." + name; - } - T result = pool.FindSymbol(name); - if (result != null && result.File == this) - { - return result; - } - return null; - } - - /// - /// Builds a FileDescriptor from its protocol buffer representation. - /// - /// The protocol message form of the FileDescriptor. - /// FileDescriptors corresponding to all of the - /// file's dependencies, in the exact order listed in the .proto file. May be null, - /// in which case it is treated as an empty array. - /// If is not - /// a valid descriptor. This can occur for a number of reasons, such as a field - /// having an undefined type or because two messages were defined with the same name. - public static FileDescriptor BuildFrom(FileDescriptorProto proto, FileDescriptor[] dependencies) - { - return BuildFrom(proto, dependencies, false); - } - - /// - /// Builds a FileDescriptor from its protocol buffer representation. - /// - /// The protocol message form of the FileDescriptor. - /// FileDescriptors corresponding to all of the - /// file's dependencies, in the exact order listed in the .proto file. May be null, - /// in which case it is treated as an empty array. - /// Whether unknown dependencies are ignored (true) or cause an exception to be thrown (false). - /// If is not - /// a valid descriptor. This can occur for a number of reasons, such as a field - /// having an undefined type or because two messages were defined with the same name. - private static FileDescriptor BuildFrom(FileDescriptorProto proto, FileDescriptor[] dependencies, bool allowUnknownDependencies) - { - // Building descriptors involves two steps: translating and linking. - // In the translation step (implemented by FileDescriptor's - // constructor), we build an object tree mirroring the - // FileDescriptorProto's tree and put all of the descriptors into the - // DescriptorPool's lookup tables. In the linking step, we look up all - // type references in the DescriptorPool, so that, for example, a - // FieldDescriptor for an embedded message contains a pointer directly - // to the Descriptor for that message's type. We also detect undefined - // types in the linking step. - if (dependencies == null) - { - dependencies = new FileDescriptor[0]; - } - - DescriptorPool pool = new DescriptorPool(dependencies); - FileDescriptor result = new FileDescriptor(proto, dependencies, pool, allowUnknownDependencies); - - // TODO(jonskeet): Reinstate these checks, or get rid of them entirely. They aren't in the Java code, - // and fail for the CustomOptions test right now. (We get "descriptor.proto" vs "google/protobuf/descriptor.proto".) - //if (dependencies.Length != proto.DependencyCount) - //{ - // throw new DescriptorValidationException(result, - // "Dependencies passed to FileDescriptor.BuildFrom() don't match " + - // "those listed in the FileDescriptorProto."); - //} - //for (int i = 0; i < proto.DependencyCount; i++) - //{ - // if (dependencies[i].Name != proto.DependencyList[i]) - // { - // throw new DescriptorValidationException(result, - // "Dependencies passed to FileDescriptor.BuildFrom() don't match " + - // "those listed in the FileDescriptorProto."); - // } - //} - - result.CrossLink(); - return result; - } - - private void CrossLink() - { - foreach (MessageDescriptor message in messageTypes) - { - message.CrossLink(); - } - - foreach (ServiceDescriptor service in services) - { - service.CrossLink(); - } - - foreach (FieldDescriptor extension in extensions) - { - extension.CrossLink(); - } - - foreach (MessageDescriptor message in messageTypes) - { - message.CheckRequiredFields(); - } - } - - /// - /// This method is to be called by generated code only. It is equivalent - /// to BuildFrom except that the FileDescriptorProto is encoded in - /// protocol buffer wire format. This overload is maintained for backward - /// compatibility with source code generated before the custom options were available - /// (and working). - /// - public static FileDescriptor InternalBuildGeneratedFileFrom(byte[] descriptorData, FileDescriptor[] dependencies) - { - return InternalBuildGeneratedFileFrom(descriptorData, dependencies, x => null); - } - - /// - /// This delegate should be used by generated code only. When calling - /// FileDescriptor.InternalBuildGeneratedFileFrom, the caller can provide - /// a callback which assigns the global variables defined in the generated code - /// which point at parts of the FileDescriptor. The callback returns an - /// Extension Registry which contains any extensions which might be used in - /// the descriptor - that is, extensions of the various "Options" messages defined - /// in descriptor.proto. The callback may also return null to indicate that - /// no extensions are used in the descriptor. - /// - /// - /// - public delegate ExtensionRegistry InternalDescriptorAssigner(FileDescriptor descriptor); - - public static FileDescriptor InternalBuildGeneratedFileFrom(byte[] descriptorData, - FileDescriptor[] dependencies, - InternalDescriptorAssigner descriptorAssigner) - { - FileDescriptorProto proto; - try - { - proto = FileDescriptorProto.ParseFrom(descriptorData); - } - catch (InvalidProtocolBufferException e) - { - throw new ArgumentException("Failed to parse protocol buffer descriptor for generated code.", e); - } - - FileDescriptor result; - try - { - // When building descriptors for generated code, we allow unknown - // dependencies by default. - result = BuildFrom(proto, dependencies, true); - } - catch (DescriptorValidationException e) - { - throw new ArgumentException("Invalid embedded descriptor for \"" + proto.Name + "\".", e); - } - - ExtensionRegistry registry = descriptorAssigner(result); - - if (registry != null) - { - // We must re-parse the proto using the registry. - try - { - proto = FileDescriptorProto.ParseFrom(descriptorData, registry); - } - catch (InvalidProtocolBufferException e) - { - throw new ArgumentException("Failed to parse protocol buffer descriptor for generated code.", e); - } - - result.ReplaceProto(proto); - } - return result; - } - - /// - /// Replace our FileDescriptorProto with the given one, which is - /// identical except that it might contain extensions that weren't present - /// in the original. This method is needed for bootstrapping when a file - /// defines custom options. The options may be defined in the file itself, - /// so we can't actually parse them until we've constructed the descriptors, - /// but to construct the decsriptors we have to have parsed the descriptor - /// protos. So, we have to parse the descriptor protos a second time after - /// constructing the descriptors. - /// - private void ReplaceProto(FileDescriptorProto newProto) - { - proto = newProto; - - for (int i = 0; i < messageTypes.Count; i++) - { - messageTypes[i].ReplaceProto(proto.GetMessageType(i)); - } - - for (int i = 0; i < enumTypes.Count; i++) - { - enumTypes[i].ReplaceProto(proto.GetEnumType(i)); - } - - for (int i = 0; i < services.Count; i++) - { - services[i].ReplaceProto(proto.GetService(i)); - } - - for (int i = 0; i < extensions.Count; i++) - { - extensions[i].ReplaceProto(proto.GetExtension(i)); - } - } - - public override string ToString() - { - return "FileDescriptor for " + proto.Name; - } - } +#region Copyright notice and license +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; + +namespace Google.Protobuf.Reflection +{ + /// + /// Describes a .proto file, including everything defined within. + /// IDescriptor is implemented such that the File property returns this descriptor, + /// and the FullName is the same as the Name. + /// + public sealed class FileDescriptor : IDescriptor + { + private readonly ByteString descriptorData; + private readonly FileDescriptorProto proto; + private readonly IList messageTypes; + private readonly IList enumTypes; + private readonly IList services; + private readonly IList dependencies; + private readonly IList publicDependencies; + private readonly DescriptorPool pool; + + private FileDescriptor(ByteString descriptorData, FileDescriptorProto proto, FileDescriptor[] dependencies, DescriptorPool pool, bool allowUnknownDependencies, GeneratedCodeInfo generatedCodeInfo) + { + this.descriptorData = descriptorData; + this.pool = pool; + this.proto = proto; + this.dependencies = new ReadOnlyCollection((FileDescriptor[]) dependencies.Clone()); + + publicDependencies = DeterminePublicDependencies(this, proto, dependencies, allowUnknownDependencies); + + pool.AddPackage(Package, this); + + messageTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.MessageType, + (message, index) => + new MessageDescriptor(message, this, null, index, generatedCodeInfo == null ? null : generatedCodeInfo.NestedTypes[index])); + + enumTypes = DescriptorUtil.ConvertAndMakeReadOnly(proto.EnumType, + (enumType, index) => + new EnumDescriptor(enumType, this, null, index, generatedCodeInfo == null ? null : generatedCodeInfo.NestedEnums[index])); + + services = DescriptorUtil.ConvertAndMakeReadOnly(proto.Service, + (service, index) => + new ServiceDescriptor(service, this, index)); + } + + /// + /// Computes the full name of a descriptor within this file, with an optional parent message. + /// + internal string ComputeFullName(MessageDescriptor parent, string name) + { + if (parent != null) + { + return parent.FullName + "." + name; + } + if (Package.Length > 0) + { + return Package + "." + name; + } + return name; + } + + /// + /// Extracts public dependencies from direct dependencies. This is a static method despite its + /// first parameter, as the value we're in the middle of constructing is only used for exceptions. + /// + private static IList DeterminePublicDependencies(FileDescriptor @this, FileDescriptorProto proto, FileDescriptor[] dependencies, bool allowUnknownDependencies) + { + var nameToFileMap = new Dictionary(); + foreach (var file in dependencies) + { + nameToFileMap[file.Name] = file; + } + var publicDependencies = new List(); + for (int i = 0; i < proto.PublicDependency.Count; i++) + { + int index = proto.PublicDependency[i]; + if (index < 0 || index >= proto.Dependency.Count) + { + throw new DescriptorValidationException(@this, "Invalid public dependency index."); + } + string name = proto.Dependency[index]; + FileDescriptor file = nameToFileMap[name]; + if (file == null) + { + if (!allowUnknownDependencies) + { + throw new DescriptorValidationException(@this, "Invalid public dependency: " + name); + } + // Ignore unknown dependencies. + } + else + { + publicDependencies.Add(file); + } + } + return new ReadOnlyCollection(publicDependencies); + } + + /// + /// The descriptor in its protocol message representation. + /// + internal FileDescriptorProto Proto + { + get { return proto; } + } + + /// + /// The file name. + /// + public string Name + { + get { return proto.Name; } + } + + /// + /// The package as declared in the .proto file. This may or may not + /// be equivalent to the .NET namespace of the generated classes. + /// + public string Package + { + get { return proto.Package; } + } + + /// + /// Unmodifiable list of top-level message types declared in this file. + /// + public IList MessageTypes + { + get { return messageTypes; } + } + + /// + /// Unmodifiable list of top-level enum types declared in this file. + /// + public IList EnumTypes + { + get { return enumTypes; } + } + + /// + /// Unmodifiable list of top-level services declared in this file. + /// + public IList Services + { + get { return services; } + } + + /// + /// Unmodifiable list of this file's dependencies (imports). + /// + public IList Dependencies + { + get { return dependencies; } + } + + /// + /// Unmodifiable list of this file's public dependencies (public imports). + /// + public IList PublicDependencies + { + get { return publicDependencies; } + } + + /// + /// The original serialized binary form of this descriptor. + /// + public ByteString SerializedData + { + get { return descriptorData; } + } + + /// + /// Implementation of IDescriptor.FullName - just returns the same as Name. + /// + string IDescriptor.FullName + { + get { return Name; } + } + + /// + /// Implementation of IDescriptor.File - just returns this descriptor. + /// + FileDescriptor IDescriptor.File + { + get { return this; } + } + + /// + /// Pool containing symbol descriptors. + /// + internal DescriptorPool DescriptorPool + { + get { return pool; } + } + + /// + /// Finds a type (message, enum, service or extension) in the file by name. Does not find nested types. + /// + /// The unqualified type name to look for. + /// The type of descriptor to look for + /// The type's descriptor, or null if not found. + public T FindTypeByName(String name) + where T : class, IDescriptor + { + // Don't allow looking up nested types. This will make optimization + // easier later. + if (name.IndexOf('.') != -1) + { + return null; + } + if (Package.Length > 0) + { + name = Package + "." + name; + } + T result = pool.FindSymbol(name); + if (result != null && result.File == this) + { + return result; + } + return null; + } + + /// + /// Builds a FileDescriptor from its protocol buffer representation. + /// + /// The original serialized descriptor data. + /// We have only limited proto2 support, so serializing FileDescriptorProto + /// would not necessarily give us this. + /// The protocol message form of the FileDescriptor. + /// FileDescriptors corresponding to all of the + /// file's dependencies, in the exact order listed in the .proto file. May be null, + /// in which case it is treated as an empty array. + /// Whether unknown dependencies are ignored (true) or cause an exception to be thrown (false). + /// Reflection information, if any. May be null, specifically for non-generated code. + /// If is not + /// a valid descriptor. This can occur for a number of reasons, such as a field + /// having an undefined type or because two messages were defined with the same name. + private static FileDescriptor BuildFrom(ByteString descriptorData, FileDescriptorProto proto, FileDescriptor[] dependencies, bool allowUnknownDependencies, GeneratedCodeInfo generatedCodeInfo) + { + // Building descriptors involves two steps: translating and linking. + // In the translation step (implemented by FileDescriptor's + // constructor), we build an object tree mirroring the + // FileDescriptorProto's tree and put all of the descriptors into the + // DescriptorPool's lookup tables. In the linking step, we look up all + // type references in the DescriptorPool, so that, for example, a + // FieldDescriptor for an embedded message contains a pointer directly + // to the Descriptor for that message's type. We also detect undefined + // types in the linking step. + if (dependencies == null) + { + dependencies = new FileDescriptor[0]; + } + + DescriptorPool pool = new DescriptorPool(dependencies); + FileDescriptor result = new FileDescriptor(descriptorData, proto, dependencies, pool, allowUnknownDependencies, generatedCodeInfo); + + // Validate that the dependencies we've been passed (as FileDescriptors) are actually the ones we + // need. + if (dependencies.Length != proto.Dependency.Count) + { + throw new DescriptorValidationException(result, + "Dependencies passed to FileDescriptor.BuildFrom() don't match " + + "those listed in the FileDescriptorProto."); + } + for (int i = 0; i < proto.Dependency.Count; i++) + { + if (dependencies[i].Name != proto.Dependency[i]) + { + throw new DescriptorValidationException(result, + "Dependencies passed to FileDescriptor.BuildFrom() don't match " + + "those listed in the FileDescriptorProto."); + } + } + + result.CrossLink(); + return result; + } + + private void CrossLink() + { + foreach (MessageDescriptor message in messageTypes) + { + message.CrossLink(); + } + + foreach (ServiceDescriptor service in services) + { + service.CrossLink(); + } + } + + /// + /// Creates an instance for generated code. + /// + /// + /// The parameter should be null for descriptors which don't correspond to + /// generated types. Otherwise, it should be a with nested types and nested + /// enums corresponding to the types and enums contained within the file descriptor. + /// + public static FileDescriptor InternalBuildGeneratedFileFrom(byte[] descriptorData, + FileDescriptor[] dependencies, + GeneratedCodeInfo generatedCodeInfo) + { + FileDescriptorProto proto; + try + { + proto = FileDescriptorProto.Parser.ParseFrom(descriptorData); + } + catch (InvalidProtocolBufferException e) + { + throw new ArgumentException("Failed to parse protocol buffer descriptor for generated code.", e); + } + + + + try + { + // When building descriptors for generated code, we allow unknown + // dependencies by default. + return BuildFrom(ByteString.CopyFrom(descriptorData), proto, dependencies, true, generatedCodeInfo); + } + catch (DescriptorValidationException e) + { + throw new ArgumentException("Invalid embedded descriptor for \"" + proto.Name + "\".", e); + } + } + + /// + /// Returns a that represents this instance. + /// + /// + /// A that represents this instance. + /// + public override string ToString() + { + return "FileDescriptor for " + proto.Name; + } + + /// + /// Returns the file descriptor for descriptor.proto. + /// + /// + /// This is used for protos which take a direct dependency on descriptor.proto, typically for + /// annotations. While descriptor.proto is a proto2 file, it is built into the Google.Protobuf + /// runtime for reflection purposes. The messages are internal to the runtime as they would require + /// proto2 semantics for full support, but the file descriptor is available via this property. The + /// C# codegen in protoc automatically uses this property when it detects a dependency on descriptor.proto. + /// + /// + /// The file descriptor for descriptor.proto. + /// + public static FileDescriptor DescriptorProtoFileDescriptor { get { return DescriptorProtoFile.Descriptor; } } + } } \ No newline at end of file diff --git a/csharp/src/Google.Protobuf/Reflection/GeneratedCodeInfo.cs b/csharp/src/Google.Protobuf/Reflection/GeneratedCodeInfo.cs new file mode 100644 index 0000000000000..8c52cd124852c --- /dev/null +++ b/csharp/src/Google.Protobuf/Reflection/GeneratedCodeInfo.cs @@ -0,0 +1,66 @@ +using System; + +namespace Google.Protobuf.Reflection +{ + /// + /// Extra information provided by generated code when initializing a message or file descriptor. + /// These are constructed as required, and are not long-lived. Hand-written code should + /// never need to use this type. + /// + public sealed class GeneratedCodeInfo + { + private static readonly string[] EmptyNames = new string[0]; + private static readonly GeneratedCodeInfo[] EmptyCodeInfo = new GeneratedCodeInfo[0]; + + /// + /// Irrelevant for file descriptors; the CLR type for the message for message descriptors. + /// + public Type ClrType { get; private set; } + + /// + /// Irrelevant for file descriptors; the CLR property names (in message descriptor field order) + /// for fields in the message for message descriptors. + /// + public string[] PropertyNames { get; private set; } + + /// + /// Irrelevant for file descriptors; the CLR property "base" names (in message descriptor oneof order) + /// for oneofs in the message for message descriptors. It is expected that for a oneof name of "Foo", + /// there will be a "FooCase" property and a "ClearFoo" method. + /// + public string[] OneofNames { get; private set; } + + /// + /// The reflection information for types within this file/message descriptor. Elements may be null + /// if there is no corresponding generated type, e.g. for map entry types. + /// + public GeneratedCodeInfo[] NestedTypes { get; private set; } + + /// + /// The CLR types for enums within this file/message descriptor. + /// + public Type[] NestedEnums { get; private set; } + + /// + /// Creates a GeneratedCodeInfo for a message descriptor, with nested types, nested enums, the CLR type, property names and oneof names. + /// Each array parameter may be null, to indicate a lack of values. + /// The parameter order is designed to make it feasible to format the generated code readably. + /// + public GeneratedCodeInfo(Type clrType, string[] propertyNames, string[] oneofNames, Type[] nestedEnums, GeneratedCodeInfo[] nestedTypes) + { + NestedTypes = nestedTypes ?? EmptyCodeInfo; + NestedEnums = nestedEnums ?? ReflectionUtil.EmptyTypes; + ClrType = clrType; + PropertyNames = propertyNames ?? EmptyNames; + OneofNames = oneofNames ?? EmptyNames; + } + + /// + /// Creates a GeneratedCodeInfo for a file descriptor, with only types and enums. + /// + public GeneratedCodeInfo(Type[] nestedEnums, GeneratedCodeInfo[] nestedTypes) + : this(null, null, null, nestedEnums, nestedTypes) + { + } + } +} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers/Descriptors/IDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/IDescriptor.cs similarity index 72% rename from csharp/src/ProtocolBuffers/Descriptors/IDescriptor.cs rename to csharp/src/Google.Protobuf/Reflection/IDescriptor.cs index 899c15607dbb8..318d58c968a58 100644 --- a/csharp/src/ProtocolBuffers/Descriptors/IDescriptor.cs +++ b/csharp/src/Google.Protobuf/Reflection/IDescriptor.cs @@ -1,55 +1,55 @@ -// 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. - -namespace Google.ProtocolBuffers.Descriptors -{ - /// - /// The non-generic form of the IDescriptor interface. Useful for describing a general - /// descriptor. - /// - public interface IDescriptor - { - string Name { get; } - string FullName { get; } - FileDescriptor File { get; } - IMessage Proto { get; } - } - - /// - /// Strongly-typed form of the IDescriptor interface. - /// - /// Protocol buffer type underlying this descriptor type - public interface IDescriptor : IDescriptor where TProto : IMessage - { - new TProto Proto { get; } - } +#region Copyright notice and license +// 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. +#endregion + +namespace Google.Protobuf.Reflection +{ + /// + /// Interface implemented by all descriptor types. + /// + public interface IDescriptor + { + /// + /// Returns the name of the entity (message, field etc) being described. + /// + string Name { get; } + + /// + /// Returns the fully-qualified name of the entity being described. + /// + string FullName { get; } + + /// + /// Returns the descriptor for the .proto file that this entity is part of. + /// + FileDescriptor File { get; } + } } \ No newline at end of file diff --git a/csharp/src/Google.Protobuf/Reflection/IFieldAccessor.cs b/csharp/src/Google.Protobuf/Reflection/IFieldAccessor.cs new file mode 100644 index 0000000000000..cfe56fde671e4 --- /dev/null +++ b/csharp/src/Google.Protobuf/Reflection/IFieldAccessor.cs @@ -0,0 +1,71 @@ +#region Copyright notice and license +// 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. +#endregion + +using System; +using System.Collections; + +namespace Google.Protobuf.Reflection +{ + /// + /// Allows fields to be reflectively accessed. + /// + public interface IFieldAccessor + { + /// + /// Returns the descriptor associated with this field. + /// + FieldDescriptor Descriptor { get; } + + /// + /// Clears the field in the specified message. (For repeated fields, + /// this clears the list.) + /// + void Clear(IMessage message); + + /// + /// Fetches the field value. For repeated values, this will be an + /// implementation. For map values, this will be an + /// implementation. + /// + object GetValue(IMessage message); + + /// + /// Mutator for single "simple" fields only. + /// + /// + /// Repeated fields are mutated by fetching the value and manipulating it as a list. + /// Map fields are mutated by fetching the value and manipulating it as a dictionary. + /// + /// The field is not a "simple" field. + void SetValue(IMessage message, object value); + } +} \ No newline at end of file diff --git a/csharp/src/Google.Protobuf/Reflection/MapFieldAccessor.cs b/csharp/src/Google.Protobuf/Reflection/MapFieldAccessor.cs new file mode 100644 index 0000000000000..9ed7f8c4df4c1 --- /dev/null +++ b/csharp/src/Google.Protobuf/Reflection/MapFieldAccessor.cs @@ -0,0 +1,59 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using System; +using System.Collections; +using System.Reflection; + +namespace Google.Protobuf.Reflection +{ + /// + /// Accessor for map fields. + /// + internal sealed class MapFieldAccessor : FieldAccessorBase + { + internal MapFieldAccessor(PropertyInfo property, FieldDescriptor descriptor) : base(property, descriptor) + { + } + + public override void Clear(IMessage message) + { + IDictionary list = (IDictionary) GetValue(message); + list.Clear(); + } + + public override void SetValue(IMessage message, object value) + { + throw new InvalidOperationException("SetValue is not implemented for map fields"); + } + } +} diff --git a/csharp/src/Google.Protobuf/Reflection/MessageDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/MessageDescriptor.cs new file mode 100644 index 0000000000000..82901f1b2b1b4 --- /dev/null +++ b/csharp/src/Google.Protobuf/Reflection/MessageDescriptor.cs @@ -0,0 +1,299 @@ +#region Copyright notice and license +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; + +namespace Google.Protobuf.Reflection +{ + /// + /// Describes a message type. + /// + public sealed class MessageDescriptor : DescriptorBase + { + private static readonly HashSet WellKnownTypeNames = new HashSet + { + "google/protobuf/any.proto", + "google/protobuf/api.proto", + "google/protobuf/duration.proto", + "google/protobuf/empty.proto", + "google/protobuf/wrappers.proto", + "google/protobuf/timestamp.proto", + "google/protobuf/field_mask.proto", + "google/protobuf/source_context.proto", + "google/protobuf/struct.proto", + "google/protobuf/type.proto", + }; + + private readonly DescriptorProto proto; + private readonly MessageDescriptor containingType; + private readonly IList nestedTypes; + private readonly IList enumTypes; + private readonly IList fieldsInDeclarationOrder; + private readonly IList fieldsInNumberOrder; + private readonly FieldCollection fields; + private readonly IList oneofs; + // CLR representation of the type described by this descriptor, if any. + private readonly Type generatedType; + + internal MessageDescriptor(DescriptorProto proto, FileDescriptor file, MessageDescriptor parent, int typeIndex, GeneratedCodeInfo generatedCodeInfo) + : base(file, file.ComputeFullName(parent, proto.Name), typeIndex) + { + this.proto = proto; + generatedType = generatedCodeInfo == null ? null : generatedCodeInfo.ClrType; + + containingType = parent; + + oneofs = DescriptorUtil.ConvertAndMakeReadOnly( + proto.OneofDecl, + (oneof, index) => + new OneofDescriptor(oneof, file, this, index, generatedCodeInfo == null ? null : generatedCodeInfo.OneofNames[index])); + + nestedTypes = DescriptorUtil.ConvertAndMakeReadOnly( + proto.NestedType, + (type, index) => + new MessageDescriptor(type, file, this, index, generatedCodeInfo == null ? null : generatedCodeInfo.NestedTypes[index])); + + enumTypes = DescriptorUtil.ConvertAndMakeReadOnly( + proto.EnumType, + (type, index) => + new EnumDescriptor(type, file, this, index, generatedCodeInfo == null ? null : generatedCodeInfo.NestedEnums[index])); + + fieldsInDeclarationOrder = DescriptorUtil.ConvertAndMakeReadOnly( + proto.Field, + (field, index) => + new FieldDescriptor(field, file, this, index, generatedCodeInfo == null ? null : generatedCodeInfo.PropertyNames[index])); + fieldsInNumberOrder = new ReadOnlyCollection(fieldsInDeclarationOrder.OrderBy(field => field.FieldNumber).ToArray()); + file.DescriptorPool.AddSymbol(this); + fields = new FieldCollection(this); + } + + /// + /// Returns the total number of nested types and enums, recursively. + /// + private int CountTotalGeneratedTypes() + { + return nestedTypes.Sum(nested => nested.CountTotalGeneratedTypes()) + enumTypes.Count; + } + + /// + /// The brief name of the descriptor's target. + /// + public override string Name { get { return proto.Name; } } + + internal DescriptorProto Proto { get { return proto; } } + + /// + /// The generated type for this message, or null if the descriptor does not represent a generated type. + /// + public Type GeneratedType { get { return generatedType; } } + + /// + /// Returns whether this message is one of the "well known types" which may have runtime/protoc support. + /// + internal bool IsWellKnownType + { + get + { + return File.Package == "google.protobuf" && WellKnownTypeNames.Contains(File.Name); + } + } + + /// + /// If this is a nested type, get the outer descriptor, otherwise null. + /// + public MessageDescriptor ContainingType + { + get { return containingType; } + } + + /// + /// A collection of fields, which can be retrieved by name or field number. + /// + public FieldCollection Fields + { + get { return fields; } + } + + /// + /// An unmodifiable list of this message type's nested types. + /// + public IList NestedTypes + { + get { return nestedTypes; } + } + + /// + /// An unmodifiable list of this message type's enum types. + /// + public IList EnumTypes + { + get { return enumTypes; } + } + + /// + /// An unmodifiable list of the "oneof" field collections in this message type. + /// + public IList Oneofs + { + get { return oneofs; } + } + + /// + /// Finds a field by field name. + /// + /// The unqualified name of the field (e.g. "foo"). + /// The field's descriptor, or null if not found. + public FieldDescriptor FindFieldByName(String name) + { + return File.DescriptorPool.FindSymbol(FullName + "." + name); + } + + /// + /// Finds a field by field number. + /// + /// The field number within this message type. + /// The field's descriptor, or null if not found. + public FieldDescriptor FindFieldByNumber(int number) + { + return File.DescriptorPool.FindFieldByNumber(this, number); + } + + /// + /// Finds a nested descriptor by name. The is valid for fields, nested + /// message types, oneofs and enums. + /// + /// The unqualified name of the descriptor, e.g. "Foo" + /// The descriptor, or null if not found. + public T FindDescriptor(string name) + where T : class, IDescriptor + { + return File.DescriptorPool.FindSymbol(FullName + "." + name); + } + + /// + /// Looks up and cross-links all fields and nested types. + /// + internal void CrossLink() + { + foreach (MessageDescriptor message in nestedTypes) + { + message.CrossLink(); + } + + foreach (FieldDescriptor field in fieldsInDeclarationOrder) + { + field.CrossLink(); + } + + foreach (OneofDescriptor oneof in oneofs) + { + oneof.CrossLink(); + } + } + + /// + /// A collection to simplify retrieving the field accessor for a particular field. + /// + public sealed class FieldCollection + { + private readonly MessageDescriptor messageDescriptor; + + internal FieldCollection(MessageDescriptor messageDescriptor) + { + this.messageDescriptor = messageDescriptor; + } + + /// + /// Returns the fields in the message as an immutable list, in the order in which they + /// are declared in the source .proto file. + /// + public IList InDeclarationOrder() + { + return messageDescriptor.fieldsInDeclarationOrder; + } + + /// + /// Returns the fields in the message as an immutable list, in ascending field number + /// order. Field numbers need not be contiguous, so there is no direct mapping from the + /// index in the list to the field number; to retrieve a field by field number, it is better + /// to use the indexer. + /// + public IList InFieldNumberOrder() + { + return messageDescriptor.fieldsInNumberOrder; + } + + /// + /// Retrieves the descriptor for the field with the given number. + /// + /// Number of the field to retrieve the descriptor for + /// The accessor for the given field + /// The message descriptor does not contain a field + /// with the given number + public FieldDescriptor this[int number] + { + get + { + var fieldDescriptor = messageDescriptor.FindFieldByNumber(number); + if (fieldDescriptor == null) + { + throw new KeyNotFoundException("No such field number"); + } + return fieldDescriptor; + } + } + + /// + /// Retrieves the descriptor for the field with the given name. + /// + /// Name of the field to retrieve the descriptor for + /// The descriptor for the given field + /// The message descriptor does not contain a field + /// with the given name + public FieldDescriptor this[string name] + { + get + { + var fieldDescriptor = messageDescriptor.FindFieldByName(name); + if (fieldDescriptor == null) + { + throw new KeyNotFoundException("No such field name"); + } + return fieldDescriptor; + } + } + } + } +} diff --git a/csharp/src/ProtocolBuffers/Descriptors/MethodDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/MethodDescriptor.cs similarity index 72% rename from csharp/src/ProtocolBuffers/Descriptors/MethodDescriptor.cs rename to csharp/src/Google.Protobuf/Reflection/MethodDescriptor.cs index f9ede24518a25..f9539f6cbdc2d 100644 --- a/csharp/src/ProtocolBuffers/Descriptors/MethodDescriptor.cs +++ b/csharp/src/Google.Protobuf/Reflection/MethodDescriptor.cs @@ -1,94 +1,103 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -using Google.ProtocolBuffers.DescriptorProtos; - -namespace Google.ProtocolBuffers.Descriptors -{ - /// - /// Describes a single method in a service. - /// - public sealed class MethodDescriptor : IndexedDescriptorBase - { - private readonly ServiceDescriptor service; - private MessageDescriptor inputType; - private MessageDescriptor outputType; - - /// - /// The service this method belongs to. - /// - public ServiceDescriptor Service - { - get { return service; } - } - - /// - /// The method's input type. - /// - public MessageDescriptor InputType - { - get { return inputType; } - } - - /// - /// The method's input type. - /// - public MessageDescriptor OutputType - { - get { return outputType; } - } - - internal MethodDescriptor(MethodDescriptorProto proto, FileDescriptor file, - ServiceDescriptor parent, int index) - : base(proto, file, parent.FullName + "." + proto.Name, index) - { - service = parent; - file.DescriptorPool.AddSymbol(this); - } - - internal void CrossLink() - { - IDescriptor lookup = File.DescriptorPool.LookupSymbol(Proto.InputType, this); - if (!(lookup is MessageDescriptor)) - { - throw new DescriptorValidationException(this, "\"" + Proto.InputType + "\" is not a message type."); - } - inputType = (MessageDescriptor) lookup; - - lookup = File.DescriptorPool.LookupSymbol(Proto.OutputType, this); - if (!(lookup is MessageDescriptor)) - { - throw new DescriptorValidationException(this, "\"" + Proto.OutputType + "\" is not a message type."); - } - outputType = (MessageDescriptor) lookup; - } - } +#region Copyright notice and license +// 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. +#endregion + +namespace Google.Protobuf.Reflection +{ + /// + /// Describes a single method in a service. + /// + public sealed class MethodDescriptor : DescriptorBase + { + private readonly MethodDescriptorProto proto; + private readonly ServiceDescriptor service; + private MessageDescriptor inputType; + private MessageDescriptor outputType; + + /// + /// The service this method belongs to. + /// + public ServiceDescriptor Service { get { return service; } } + + /// + /// The method's input type. + /// + public MessageDescriptor InputType { get { return inputType; } } + + /// + /// The method's input type. + /// + public MessageDescriptor OutputType { get { return outputType; } } + + /// + /// Indicates if client streams multiple requests. + /// + public bool IsClientStreaming { get { return proto.ClientStreaming; } } + + /// + /// Indicates if server streams multiple responses. + /// + public bool IsServerStreaming { get { return proto.ServerStreaming; } } + + internal MethodDescriptor(MethodDescriptorProto proto, FileDescriptor file, + ServiceDescriptor parent, int index) + : base(file, parent.FullName + "." + proto.Name, index) + { + this.proto = proto; + service = parent; + file.DescriptorPool.AddSymbol(this); + } + + internal MethodDescriptorProto Proto { get { return proto; } } + + /// + /// The brief name of the descriptor's target. + /// + public override string Name { get { return proto.Name; } } + + internal void CrossLink() + { + IDescriptor lookup = File.DescriptorPool.LookupSymbol(Proto.InputType, this); + if (!(lookup is MessageDescriptor)) + { + throw new DescriptorValidationException(this, "\"" + Proto.InputType + "\" is not a message type."); + } + inputType = (MessageDescriptor) lookup; + + lookup = File.DescriptorPool.LookupSymbol(Proto.OutputType, this); + if (!(lookup is MessageDescriptor)) + { + throw new DescriptorValidationException(this, "\"" + Proto.OutputType + "\" is not a message type."); + } + outputType = (MessageDescriptor) lookup; + } + } } \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers/FieldAccess/OneofAccessor.cs b/csharp/src/Google.Protobuf/Reflection/OneofAccessor.cs similarity index 53% rename from csharp/src/ProtocolBuffers/FieldAccess/OneofAccessor.cs rename to csharp/src/Google.Protobuf/Reflection/OneofAccessor.cs index 1a4bda76b7c17..8714ab18efe7c 100644 --- a/csharp/src/ProtocolBuffers/FieldAccess/OneofAccessor.cs +++ b/csharp/src/Google.Protobuf/Reflection/OneofAccessor.cs @@ -1,91 +1,90 @@ -// 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 -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -using System; -using System.Reflection; -using Google.ProtocolBuffers.Descriptors; - -namespace Google.ProtocolBuffers.FieldAccess -{ - /// - /// Access for an oneof - /// - internal class OneofAccessor - where TMessage : IMessage - where TBuilder : IBuilder - { - private readonly Func caseDelegate; - private readonly Func clearDelegate; - private MessageDescriptor descriptor; - - internal OneofAccessor(MessageDescriptor descriptor, string name) - { - this.descriptor = descriptor; - MethodInfo clearMethod = typeof(TBuilder).GetMethod("Clear" + name); - PropertyInfo caseProperty = typeof(TMessage).GetProperty(name + "Case"); - if (clearMethod == null || caseProperty == null) - { - throw new ArgumentException("Not all required properties/methods available for oneof"); - } - - - clearDelegate = ReflectionUtil.CreateDelegateFunc(clearMethod); - caseDelegate = ReflectionUtil.CreateUpcastDelegate(caseProperty.GetGetMethod()); - } - - /// - /// Indicates whether the specified message has set any field in the oneof. - /// - public bool Has(TMessage message) - { - return ((int) caseDelegate(message) != 0); - } - - /// - /// Clears the oneof in the specified builder. - /// - public void Clear(TBuilder builder) - { - clearDelegate(builder); - } - - /// - /// Indicates which field in the oneof is set for specified message - /// - public virtual FieldDescriptor GetOneofFieldDescriptor(TMessage message) - { - int fieldNumber = (int) caseDelegate(message); - if (fieldNumber > 0) - { - return descriptor.FindFieldByNumber(fieldNumber); - } - return null; - } - } -} +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using System; +using System.Reflection; +using Google.Protobuf.Compatibility; + +namespace Google.Protobuf.Reflection +{ + /// + /// Reflection access for a oneof, allowing clear and "get case" actions. + /// + public sealed class OneofAccessor + { + private readonly Func caseDelegate; + private readonly Action clearDelegate; + private OneofDescriptor descriptor; + + internal OneofAccessor(PropertyInfo caseProperty, MethodInfo clearMethod, OneofDescriptor descriptor) + { + if (!caseProperty.CanRead) + { + throw new ArgumentException("Cannot read from property"); + } + this.descriptor = descriptor; + caseDelegate = ReflectionUtil.CreateFuncIMessageT(caseProperty.GetGetMethod()); + + this.descriptor = descriptor; + clearDelegate = ReflectionUtil.CreateActionIMessage(clearMethod); + } + + /// + /// Gets the descriptor for this oneof. + /// + /// + /// The descriptor of the oneof. + /// + public OneofDescriptor Descriptor { get { return descriptor; } } + + /// + /// Clears the oneof in the specified message. + /// + public void Clear(IMessage message) + { + clearDelegate(message); + } + + /// + /// Indicates which field in the oneof is set for specified message + /// + public FieldDescriptor GetCaseFieldDescriptor(IMessage message) + { + int fieldNumber = caseDelegate(message); + if (fieldNumber > 0) + { + return descriptor.ContainingType.FindFieldByNumber(fieldNumber); + } + return null; + } + } +} diff --git a/csharp/src/Google.Protobuf/Reflection/OneofDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/OneofDescriptor.cs new file mode 100644 index 0000000000000..d51ee5261d3ce --- /dev/null +++ b/csharp/src/Google.Protobuf/Reflection/OneofDescriptor.cs @@ -0,0 +1,127 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using System.Collections.Generic; +using System.Collections.ObjectModel; +using Google.Protobuf.Compatibility; + +namespace Google.Protobuf.Reflection +{ + /// + /// Describes a "oneof" field collection in a message type: a set of + /// fields of which at most one can be set in any particular message. + /// + public sealed class OneofDescriptor : DescriptorBase + { + private readonly OneofDescriptorProto proto; + private MessageDescriptor containingType; + private IList fields; + private readonly OneofAccessor accessor; + + internal OneofDescriptor(OneofDescriptorProto proto, FileDescriptor file, MessageDescriptor parent, int index, string clrName) + : base(file, file.ComputeFullName(parent, proto.Name), index) + { + this.proto = proto; + containingType = parent; + + file.DescriptorPool.AddSymbol(this); + accessor = CreateAccessor(clrName); + } + + /// + /// The brief name of the descriptor's target. + /// + public override string Name { get { return proto.Name; } } + + /// + /// Gets the message type containing this oneof. + /// + /// + /// The message type containing this oneof. + /// + public MessageDescriptor ContainingType + { + get { return containingType; } + } + + /// + /// Gets the fields within this oneof, in declaration order. + /// + /// + /// The fields within this oneof, in declaration order. + /// + public IList Fields { get { return fields; } } + + /// + /// Gets an accessor for reflective access to the values associated with the oneof + /// in a particular message. + /// + /// + /// The accessor used for reflective access, or null if reflection is not + /// supported by this descriptor. + /// + public OneofAccessor Accessor { get { return accessor; } } + + internal void CrossLink() + { + List fieldCollection = new List(); + foreach (var field in ContainingType.Fields.InDeclarationOrder()) + { + if (field.ContainingOneof == this) + { + fieldCollection.Add(field); + } + } + fields = new ReadOnlyCollection(fieldCollection); + } + + private OneofAccessor CreateAccessor(string clrName) + { + if (containingType.GeneratedType == null || clrName == null) + { + return null; + } + var caseProperty = containingType.GeneratedType.GetProperty(clrName + "Case"); + if (caseProperty == null) + { + throw new DescriptorValidationException(this, "Property " + clrName + "Case not found in " + containingType.GeneratedType); + } + var clearMethod = containingType.GeneratedType.GetMethod("Clear" + clrName); + if (clearMethod == null) + { + throw new DescriptorValidationException(this, "Method Clear" + clrName + " not found in " + containingType.GeneratedType); + } + + return new OneofAccessor(caseProperty, clearMethod, this); + } + } +} diff --git a/csharp/src/ProtocolBuffers/Descriptors/PackageDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/PackageDescriptor.cs similarity index 86% rename from csharp/src/ProtocolBuffers/Descriptors/PackageDescriptor.cs rename to csharp/src/Google.Protobuf/Reflection/PackageDescriptor.cs index 02549f9c38343..e547d834986de 100644 --- a/csharp/src/ProtocolBuffers/Descriptors/PackageDescriptor.cs +++ b/csharp/src/Google.Protobuf/Reflection/PackageDescriptor.cs @@ -1,73 +1,68 @@ -// 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. - -namespace Google.ProtocolBuffers.Descriptors -{ - /// - /// Represents a package in the symbol table. We use PackageDescriptors - /// just as placeholders so that someone cannot define, say, a message type - /// that has the same name as an existing package. - /// - internal sealed class PackageDescriptor : IDescriptor - { - private readonly string name; - private readonly string fullName; - private readonly FileDescriptor file; - - internal PackageDescriptor(string name, string fullName, FileDescriptor file) - { - this.file = file; - this.fullName = fullName; - this.name = name; - } - - public IMessage Proto - { - get { return file.Proto; } - } - - public string Name - { - get { return name; } - } - - public string FullName - { - get { return fullName; } - } - - public FileDescriptor File - { - get { return file; } - } - } +#region Copyright notice and license +// 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. +#endregion + +namespace Google.Protobuf.Reflection +{ + /// + /// Represents a package in the symbol table. We use PackageDescriptors + /// just as placeholders so that someone cannot define, say, a message type + /// that has the same name as an existing package. + /// + internal sealed class PackageDescriptor : IDescriptor + { + private readonly string name; + private readonly string fullName; + private readonly FileDescriptor file; + + internal PackageDescriptor(string name, string fullName, FileDescriptor file) + { + this.file = file; + this.fullName = fullName; + this.name = name; + } + + public string Name + { + get { return name; } + } + + public string FullName + { + get { return fullName; } + } + + public FileDescriptor File + { + get { return file; } + } + } } \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers/GeneratedSingleExtension.cs b/csharp/src/Google.Protobuf/Reflection/PartialClasses.cs similarity index 60% rename from csharp/src/ProtocolBuffers/GeneratedSingleExtension.cs rename to csharp/src/Google.Protobuf/Reflection/PartialClasses.cs index f0f1979b25787..8c055d6d921ee 100644 --- a/csharp/src/ProtocolBuffers/GeneratedSingleExtension.cs +++ b/csharp/src/Google.Protobuf/Reflection/PartialClasses.cs @@ -1,10 +1,7 @@ #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/ +// 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 @@ -31,35 +28,32 @@ // 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; - -namespace Google.ProtocolBuffers +// This file just contains partial classes for any autogenerated classes that need additional support. +namespace Google.Protobuf.Reflection { - /// - /// Generated extension for a singular field. - /// - public sealed class GeneratedSingleExtension : GeneratedExtensionBase + internal partial class FieldDescriptorProto { - internal GeneratedSingleExtension(FieldDescriptor descriptor) : base(descriptor, typeof(TExtension)) - { - } - - public static GeneratedSingleExtension CreateInstance(FieldDescriptor descriptor) + // We can't tell the difference between "explicitly set to 0" and "not set" + // in proto3, but we need to tell the difference for OneofIndex. descriptor.proto + // is really a proto2 file, but the runtime doesn't know about proto2 semantics... + // We fake it by defaulting to -1. + partial void OnConstruction() { - if (descriptor.IsRepeated) - { - throw new ArgumentException("Must call GeneratedRepeateExtension.CreateInstance() for repeated types."); - } - return new GeneratedSingleExtension(descriptor); + OneofIndex = -1; } + } - public override object FromReflectionType(object value) + internal partial class FieldOptions + { + // We can't tell the difference between "explicitly set to false" and "not set" + // in proto3, but we need to tell the difference for FieldDescriptor.IsPacked. + // This won't work if we ever need to support proto2, but at that point we'll be + // able to remove this hack and use field presence instead. + partial void OnConstruction() { - return base.SingularFromReflectionType(value); + Packed = true; } } } \ No newline at end of file diff --git a/csharp/src/Google.Protobuf/Reflection/ReflectionUtil.cs b/csharp/src/Google.Protobuf/Reflection/ReflectionUtil.cs new file mode 100644 index 0000000000000..df820ca36bd8e --- /dev/null +++ b/csharp/src/Google.Protobuf/Reflection/ReflectionUtil.cs @@ -0,0 +1,107 @@ +#region Copyright notice and license +// 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Linq.Expressions; +using System.Reflection; + +namespace Google.Protobuf.Reflection +{ + /// + /// The methods in this class are somewhat evil, and should not be tampered with lightly. + /// Basically they allow the creation of relatively weakly typed delegates from MethodInfos + /// which are more strongly typed. They do this by creating an appropriate strongly typed + /// delegate from the MethodInfo, and then calling that within an anonymous method. + /// Mind-bending stuff (at least to your humble narrator) but the resulting delegates are + /// very fast compared with calling Invoke later on. + /// + internal static class ReflectionUtil + { + /// + /// Empty Type[] used when calling GetProperty to force property instead of indexer fetching. + /// + internal static readonly Type[] EmptyTypes = new Type[0]; + + /// + /// Creates a delegate which will cast the argument to the appropriate method target type, + /// call the method on it, then convert the result to object. + /// + internal static Func CreateFuncIMessageObject(MethodInfo method) + { + ParameterExpression parameter = Expression.Parameter(typeof(IMessage), "p"); + Expression downcast = Expression.Convert(parameter, method.DeclaringType); + Expression call = Expression.Call(downcast, method); + Expression upcast = Expression.Convert(call, typeof(object)); + return Expression.Lambda>(upcast, parameter).Compile(); + } + + /// + /// Creates a delegate which will cast the argument to the appropriate method target type, + /// call the method on it, then convert the result to the specified type. + /// + internal static Func CreateFuncIMessageT(MethodInfo method) + { + ParameterExpression parameter = Expression.Parameter(typeof(IMessage), "p"); + Expression downcast = Expression.Convert(parameter, method.DeclaringType); + Expression call = Expression.Call(downcast, method); + Expression upcast = Expression.Convert(call, typeof(T)); + return Expression.Lambda>(upcast, parameter).Compile(); + } + + /// + /// Creates a delegate which will execute the given method after casting the first argument to + /// the target type of the method, and the second argument to the first parameter type of the method. + /// + internal static Action CreateActionIMessageObject(MethodInfo method) + { + ParameterExpression targetParameter = Expression.Parameter(typeof(IMessage), "target"); + ParameterExpression argParameter = Expression.Parameter(typeof(object), "arg"); + Expression castTarget = Expression.Convert(targetParameter, method.DeclaringType); + Expression castArgument = Expression.Convert(argParameter, method.GetParameters()[0].ParameterType); + Expression call = Expression.Call(castTarget, method, castArgument); + return Expression.Lambda>(call, targetParameter, argParameter).Compile(); + } + + /// + /// Creates a delegate which will execute the given method after casting the first argument to + /// the target type of the method. + /// + internal static Action CreateActionIMessage(MethodInfo method) + { + ParameterExpression targetParameter = Expression.Parameter(typeof(IMessage), "target"); + Expression castTarget = Expression.Convert(targetParameter, method.DeclaringType); + Expression call = Expression.Call(castTarget, method); + return Expression.Lambda>(call, targetParameter).Compile(); + } + } +} \ No newline at end of file diff --git a/csharp/src/Google.Protobuf/Reflection/RepeatedFieldAccessor.cs b/csharp/src/Google.Protobuf/Reflection/RepeatedFieldAccessor.cs new file mode 100644 index 0000000000000..bd408470929bf --- /dev/null +++ b/csharp/src/Google.Protobuf/Reflection/RepeatedFieldAccessor.cs @@ -0,0 +1,60 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using System; +using System.Collections; +using System.Reflection; + +namespace Google.Protobuf.Reflection +{ + /// + /// Accessor for repeated fields. + /// + internal sealed class RepeatedFieldAccessor : FieldAccessorBase + { + internal RepeatedFieldAccessor(PropertyInfo property, FieldDescriptor descriptor) : base(property, descriptor) + { + } + + public override void Clear(IMessage message) + { + IList list = (IList) GetValue(message); + list.Clear(); + } + + public override void SetValue(IMessage message, object value) + { + throw new InvalidOperationException("SetValue is not implemented for repeated fields"); + } + + } +} diff --git a/csharp/src/ProtocolBuffers/Descriptors/ServiceDescriptor.cs b/csharp/src/Google.Protobuf/Reflection/ServiceDescriptor.cs similarity index 76% rename from csharp/src/ProtocolBuffers/Descriptors/ServiceDescriptor.cs rename to csharp/src/Google.Protobuf/Reflection/ServiceDescriptor.cs index 417c083867b24..cc0a50104241a 100644 --- a/csharp/src/ProtocolBuffers/Descriptors/ServiceDescriptor.cs +++ b/csharp/src/Google.Protobuf/Reflection/ServiceDescriptor.cs @@ -1,89 +1,89 @@ -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -using System; -using System.Collections.Generic; -using Google.ProtocolBuffers.DescriptorProtos; - -namespace Google.ProtocolBuffers.Descriptors -{ - /// - /// Describes a service type. - /// - public sealed class ServiceDescriptor : IndexedDescriptorBase - { - private readonly IList methods; - - public ServiceDescriptor(ServiceDescriptorProto proto, FileDescriptor file, int index) - : base(proto, file, ComputeFullName(file, null, proto.Name), index) - { - methods = DescriptorUtil.ConvertAndMakeReadOnly(proto.MethodList, - (method, i) => new MethodDescriptor(method, file, this, i)); - - file.DescriptorPool.AddSymbol(this); - } - - /// - /// An unmodifiable list of methods in this service. - /// - public IList Methods - { - get { return methods; } - } - - /// - /// Finds a method by name. - /// - /// The unqualified name of the method (e.g. "Foo"). - /// The method's decsriptor, or null if not found. - public MethodDescriptor FindMethodByName(String name) - { - return File.DescriptorPool.FindSymbol(FullName + "." + name); - } - - internal void CrossLink() - { - foreach (MethodDescriptor method in methods) - { - method.CrossLink(); - } - } - - internal override void ReplaceProto(ServiceDescriptorProto newProto) - { - base.ReplaceProto(newProto); - for (int i = 0; i < methods.Count; i++) - { - methods[i].ReplaceProto(newProto.GetMethod(i)); - } - } - } +#region Copyright notice and license +// 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. +#endregion + +using System; +using System.Collections.Generic; + +namespace Google.Protobuf.Reflection +{ + /// + /// Describes a service type. + /// + public sealed class ServiceDescriptor : DescriptorBase + { + private readonly ServiceDescriptorProto proto; + private readonly IList methods; + + internal ServiceDescriptor(ServiceDescriptorProto proto, FileDescriptor file, int index) + : base(file, file.ComputeFullName(null, proto.Name), index) + { + this.proto = proto; + methods = DescriptorUtil.ConvertAndMakeReadOnly(proto.Method, + (method, i) => new MethodDescriptor(method, file, this, i)); + + file.DescriptorPool.AddSymbol(this); + } + + /// + /// The brief name of the descriptor's target. + /// + public override string Name { get { return proto.Name; } } + + internal ServiceDescriptorProto Proto { get { return proto; } } + + /// + /// An unmodifiable list of methods in this service. + /// + public IList Methods + { + get { return methods; } + } + + /// + /// Finds a method by name. + /// + /// The unqualified name of the method (e.g. "Foo"). + /// The method's decsriptor, or null if not found. + public MethodDescriptor FindMethodByName(String name) + { + return File.DescriptorPool.FindSymbol(FullName + "." + name); + } + + internal void CrossLink() + { + foreach (MethodDescriptor method in methods) + { + method.CrossLink(); + } + } + } } \ No newline at end of file diff --git a/csharp/src/Google.Protobuf/Reflection/SingleFieldAccessor.cs b/csharp/src/Google.Protobuf/Reflection/SingleFieldAccessor.cs new file mode 100644 index 0000000000000..de92fbc1a408b --- /dev/null +++ b/csharp/src/Google.Protobuf/Reflection/SingleFieldAccessor.cs @@ -0,0 +1,81 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using System; +using System.Reflection; +using Google.Protobuf.Compatibility; + +namespace Google.Protobuf.Reflection +{ + /// + /// Accessor for single fields. + /// + internal sealed class SingleFieldAccessor : FieldAccessorBase + { + // All the work here is actually done in the constructor - it creates the appropriate delegates. + // There are various cases to consider, based on the property type (message, string/bytes, or "genuine" primitive) + // and proto2 vs proto3 for non-message types, as proto3 doesn't support "full" presence detection or default + // values. + + private readonly Action setValueDelegate; + private readonly Action clearDelegate; + + internal SingleFieldAccessor(PropertyInfo property, FieldDescriptor descriptor) : base(property, descriptor) + { + if (!property.CanWrite) + { + throw new ArgumentException("Not all required properties/methods available"); + } + setValueDelegate = ReflectionUtil.CreateActionIMessageObject(property.GetSetMethod()); + + var clrType = property.PropertyType; + + // TODO: Validate that this is a reasonable single field? (Should be a value type, a message type, or string/ByteString.) + object defaultValue = + typeof(IMessage).IsAssignableFrom(clrType) ? null + : clrType == typeof(string) ? "" + : clrType == typeof(ByteString) ? ByteString.Empty + : Activator.CreateInstance(clrType); + clearDelegate = message => SetValue(message, defaultValue); + } + + public override void Clear(IMessage message) + { + clearDelegate(message); + } + + public override void SetValue(IMessage message, object value) + { + setValueDelegate(message, value); + } + } +} diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Any.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Any.cs new file mode 100644 index 0000000000000..204b37cf094ee --- /dev/null +++ b/csharp/src/Google.Protobuf/WellKnownTypes/Any.cs @@ -0,0 +1,173 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/any.proto +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace Google.Protobuf.WellKnownTypes { + + namespace Proto { + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public static partial class Any { + + #region Descriptor + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static Any() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "Chlnb29nbGUvcHJvdG9idWYvYW55LnByb3RvEg9nb29nbGUucHJvdG9idWYi", + "JgoDQW55EhAKCHR5cGVfdXJsGAEgASgJEg0KBXZhbHVlGAIgASgMQksKE2Nv", + "bS5nb29nbGUucHJvdG9idWZCCEFueVByb3RvUAGgAQGiAgNHUEKqAh5Hb29n", + "bGUuUHJvdG9idWYuV2VsbEtub3duVHlwZXNiBnByb3RvMw==")); + descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] { + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Any), new[]{ "TypeUrl", "Value" }, null, null, null) + })); + } + #endregion + + } + } + #region Messages + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public sealed partial class Any : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Any()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.WellKnownTypes.Proto.Any.Descriptor.MessageTypes[0]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public Any() { + OnConstruction(); + } + + partial void OnConstruction(); + + public Any(Any other) : this() { + typeUrl_ = other.typeUrl_; + value_ = other.value_; + } + + public Any Clone() { + return new Any(this); + } + + public const int TypeUrlFieldNumber = 1; + private string typeUrl_ = ""; + public string TypeUrl { + get { return typeUrl_; } + set { + typeUrl_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int ValueFieldNumber = 2; + private pb::ByteString value_ = pb::ByteString.Empty; + public pb::ByteString Value { + get { return value_; } + set { + value_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public override bool Equals(object other) { + return Equals(other as Any); + } + + public bool Equals(Any other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (TypeUrl != other.TypeUrl) return false; + if (Value != other.Value) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (TypeUrl.Length != 0) hash ^= TypeUrl.GetHashCode(); + if (Value.Length != 0) hash ^= Value.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (TypeUrl.Length != 0) { + output.WriteRawTag(10); + output.WriteString(TypeUrl); + } + if (Value.Length != 0) { + output.WriteRawTag(18); + output.WriteBytes(Value); + } + } + + public int CalculateSize() { + int size = 0; + if (TypeUrl.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(TypeUrl); + } + if (Value.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeBytesSize(Value); + } + return size; + } + + public void MergeFrom(Any other) { + if (other == null) { + return; + } + if (other.TypeUrl.Length != 0) { + TypeUrl = other.TypeUrl; + } + if (other.Value.Length != 0) { + Value = other.Value; + } + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 10: { + TypeUrl = input.ReadString(); + break; + } + case 18: { + Value = input.ReadBytes(); + break; + } + } + } + } + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Api.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Api.cs new file mode 100644 index 0000000000000..a5f950938faed --- /dev/null +++ b/csharp/src/Google.Protobuf/WellKnownTypes/Api.cs @@ -0,0 +1,475 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/api.proto +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace Google.Protobuf.WellKnownTypes { + + namespace Proto { + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public static partial class Api { + + #region Descriptor + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static Api() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "Chlnb29nbGUvcHJvdG9idWYvYXBpLnByb3RvEg9nb29nbGUucHJvdG9idWYa", + "JGdvb2dsZS9wcm90b2J1Zi9zb3VyY2VfY29udGV4dC5wcm90bxoaZ29vZ2xl", + "L3Byb3RvYnVmL3R5cGUucHJvdG8isAEKA0FwaRIMCgRuYW1lGAEgASgJEigK", + "B21ldGhvZHMYAiADKAsyFy5nb29nbGUucHJvdG9idWYuTWV0aG9kEigKB29w", + "dGlvbnMYAyADKAsyFy5nb29nbGUucHJvdG9idWYuT3B0aW9uEg8KB3ZlcnNp", + "b24YBCABKAkSNgoOc291cmNlX2NvbnRleHQYBSABKAsyHi5nb29nbGUucHJv", + "dG9idWYuU291cmNlQ29udGV4dCKsAQoGTWV0aG9kEgwKBG5hbWUYASABKAkS", + "GAoQcmVxdWVzdF90eXBlX3VybBgCIAEoCRIZChFyZXF1ZXN0X3N0cmVhbWlu", + "ZxgDIAEoCBIZChFyZXNwb25zZV90eXBlX3VybBgEIAEoCRIaChJyZXNwb25z", + "ZV9zdHJlYW1pbmcYBSABKAgSKAoHb3B0aW9ucxgGIAMoCzIXLmdvb2dsZS5w", + "cm90b2J1Zi5PcHRpb25CSAoTY29tLmdvb2dsZS5wcm90b2J1ZkIIQXBpUHJv", + "dG9QAaICA0dQQqoCHkdvb2dsZS5Qcm90b2J1Zi5XZWxsS25vd25UeXBlc2IG", + "cHJvdG8z")); + descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, + new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.Proto.SourceContext.Descriptor, global::Google.Protobuf.WellKnownTypes.Proto.Type.Descriptor, }, + new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] { + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Api), new[]{ "Name", "Methods", "Options", "Version", "SourceContext" }, null, null, null), + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Method), new[]{ "Name", "RequestTypeUrl", "RequestStreaming", "ResponseTypeUrl", "ResponseStreaming", "Options" }, null, null, null) + })); + } + #endregion + + } + } + #region Messages + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public sealed partial class Api : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Api()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.WellKnownTypes.Proto.Api.Descriptor.MessageTypes[0]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public Api() { + OnConstruction(); + } + + partial void OnConstruction(); + + public Api(Api other) : this() { + name_ = other.name_; + methods_ = other.methods_.Clone(); + options_ = other.options_.Clone(); + version_ = other.version_; + SourceContext = other.sourceContext_ != null ? other.SourceContext.Clone() : null; + } + + public Api Clone() { + return new Api(this); + } + + public const int NameFieldNumber = 1; + private string name_ = ""; + public string Name { + get { return name_; } + set { + name_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int MethodsFieldNumber = 2; + private static readonly pb::FieldCodec _repeated_methods_codec + = pb::FieldCodec.ForMessage(18, global::Google.Protobuf.WellKnownTypes.Method.Parser); + private readonly pbc::RepeatedField methods_ = new pbc::RepeatedField(); + public pbc::RepeatedField Methods { + get { return methods_; } + } + + public const int OptionsFieldNumber = 3; + private static readonly pb::FieldCodec _repeated_options_codec + = pb::FieldCodec.ForMessage(26, global::Google.Protobuf.WellKnownTypes.Option.Parser); + private readonly pbc::RepeatedField options_ = new pbc::RepeatedField(); + public pbc::RepeatedField Options { + get { return options_; } + } + + public const int VersionFieldNumber = 4; + private string version_ = ""; + public string Version { + get { return version_; } + set { + version_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int SourceContextFieldNumber = 5; + private global::Google.Protobuf.WellKnownTypes.SourceContext sourceContext_; + public global::Google.Protobuf.WellKnownTypes.SourceContext SourceContext { + get { return sourceContext_; } + set { + sourceContext_ = value; + } + } + + public override bool Equals(object other) { + return Equals(other as Api); + } + + public bool Equals(Api other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Name != other.Name) return false; + if(!methods_.Equals(other.methods_)) return false; + if(!options_.Equals(other.options_)) return false; + if (Version != other.Version) return false; + if (!object.Equals(SourceContext, other.SourceContext)) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (Name.Length != 0) hash ^= Name.GetHashCode(); + hash ^= methods_.GetHashCode(); + hash ^= options_.GetHashCode(); + if (Version.Length != 0) hash ^= Version.GetHashCode(); + if (sourceContext_ != null) hash ^= SourceContext.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (Name.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Name); + } + methods_.WriteTo(output, _repeated_methods_codec); + options_.WriteTo(output, _repeated_options_codec); + if (Version.Length != 0) { + output.WriteRawTag(34); + output.WriteString(Version); + } + if (sourceContext_ != null) { + output.WriteRawTag(42); + output.WriteMessage(SourceContext); + } + } + + public int CalculateSize() { + int size = 0; + if (Name.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); + } + size += methods_.CalculateSize(_repeated_methods_codec); + size += options_.CalculateSize(_repeated_options_codec); + if (Version.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Version); + } + if (sourceContext_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(SourceContext); + } + return size; + } + + public void MergeFrom(Api other) { + if (other == null) { + return; + } + if (other.Name.Length != 0) { + Name = other.Name; + } + methods_.Add(other.methods_); + options_.Add(other.options_); + if (other.Version.Length != 0) { + Version = other.Version; + } + if (other.sourceContext_ != null) { + if (sourceContext_ == null) { + sourceContext_ = new global::Google.Protobuf.WellKnownTypes.SourceContext(); + } + SourceContext.MergeFrom(other.SourceContext); + } + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 10: { + Name = input.ReadString(); + break; + } + case 18: { + methods_.AddEntriesFrom(input, _repeated_methods_codec); + break; + } + case 26: { + options_.AddEntriesFrom(input, _repeated_options_codec); + break; + } + case 34: { + Version = input.ReadString(); + break; + } + case 42: { + if (sourceContext_ == null) { + sourceContext_ = new global::Google.Protobuf.WellKnownTypes.SourceContext(); + } + input.ReadMessage(sourceContext_); + break; + } + } + } + } + + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public sealed partial class Method : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Method()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.WellKnownTypes.Proto.Api.Descriptor.MessageTypes[1]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public Method() { + OnConstruction(); + } + + partial void OnConstruction(); + + public Method(Method other) : this() { + name_ = other.name_; + requestTypeUrl_ = other.requestTypeUrl_; + requestStreaming_ = other.requestStreaming_; + responseTypeUrl_ = other.responseTypeUrl_; + responseStreaming_ = other.responseStreaming_; + options_ = other.options_.Clone(); + } + + public Method Clone() { + return new Method(this); + } + + public const int NameFieldNumber = 1; + private string name_ = ""; + public string Name { + get { return name_; } + set { + name_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int RequestTypeUrlFieldNumber = 2; + private string requestTypeUrl_ = ""; + public string RequestTypeUrl { + get { return requestTypeUrl_; } + set { + requestTypeUrl_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int RequestStreamingFieldNumber = 3; + private bool requestStreaming_; + public bool RequestStreaming { + get { return requestStreaming_; } + set { + requestStreaming_ = value; + } + } + + public const int ResponseTypeUrlFieldNumber = 4; + private string responseTypeUrl_ = ""; + public string ResponseTypeUrl { + get { return responseTypeUrl_; } + set { + responseTypeUrl_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int ResponseStreamingFieldNumber = 5; + private bool responseStreaming_; + public bool ResponseStreaming { + get { return responseStreaming_; } + set { + responseStreaming_ = value; + } + } + + public const int OptionsFieldNumber = 6; + private static readonly pb::FieldCodec _repeated_options_codec + = pb::FieldCodec.ForMessage(50, global::Google.Protobuf.WellKnownTypes.Option.Parser); + private readonly pbc::RepeatedField options_ = new pbc::RepeatedField(); + public pbc::RepeatedField Options { + get { return options_; } + } + + public override bool Equals(object other) { + return Equals(other as Method); + } + + public bool Equals(Method other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Name != other.Name) return false; + if (RequestTypeUrl != other.RequestTypeUrl) return false; + if (RequestStreaming != other.RequestStreaming) return false; + if (ResponseTypeUrl != other.ResponseTypeUrl) return false; + if (ResponseStreaming != other.ResponseStreaming) return false; + if(!options_.Equals(other.options_)) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (Name.Length != 0) hash ^= Name.GetHashCode(); + if (RequestTypeUrl.Length != 0) hash ^= RequestTypeUrl.GetHashCode(); + if (RequestStreaming != false) hash ^= RequestStreaming.GetHashCode(); + if (ResponseTypeUrl.Length != 0) hash ^= ResponseTypeUrl.GetHashCode(); + if (ResponseStreaming != false) hash ^= ResponseStreaming.GetHashCode(); + hash ^= options_.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (Name.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Name); + } + if (RequestTypeUrl.Length != 0) { + output.WriteRawTag(18); + output.WriteString(RequestTypeUrl); + } + if (RequestStreaming != false) { + output.WriteRawTag(24); + output.WriteBool(RequestStreaming); + } + if (ResponseTypeUrl.Length != 0) { + output.WriteRawTag(34); + output.WriteString(ResponseTypeUrl); + } + if (ResponseStreaming != false) { + output.WriteRawTag(40); + output.WriteBool(ResponseStreaming); + } + options_.WriteTo(output, _repeated_options_codec); + } + + public int CalculateSize() { + int size = 0; + if (Name.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); + } + if (RequestTypeUrl.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(RequestTypeUrl); + } + if (RequestStreaming != false) { + size += 1 + 1; + } + if (ResponseTypeUrl.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(ResponseTypeUrl); + } + if (ResponseStreaming != false) { + size += 1 + 1; + } + size += options_.CalculateSize(_repeated_options_codec); + return size; + } + + public void MergeFrom(Method other) { + if (other == null) { + return; + } + if (other.Name.Length != 0) { + Name = other.Name; + } + if (other.RequestTypeUrl.Length != 0) { + RequestTypeUrl = other.RequestTypeUrl; + } + if (other.RequestStreaming != false) { + RequestStreaming = other.RequestStreaming; + } + if (other.ResponseTypeUrl.Length != 0) { + ResponseTypeUrl = other.ResponseTypeUrl; + } + if (other.ResponseStreaming != false) { + ResponseStreaming = other.ResponseStreaming; + } + options_.Add(other.options_); + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 10: { + Name = input.ReadString(); + break; + } + case 18: { + RequestTypeUrl = input.ReadString(); + break; + } + case 24: { + RequestStreaming = input.ReadBool(); + break; + } + case 34: { + ResponseTypeUrl = input.ReadString(); + break; + } + case 40: { + ResponseStreaming = input.ReadBool(); + break; + } + case 50: { + options_.AddEntriesFrom(input, _repeated_options_codec); + break; + } + } + } + } + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Duration.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Duration.cs new file mode 100644 index 0000000000000..aa34f2d8cbadb --- /dev/null +++ b/csharp/src/Google.Protobuf/WellKnownTypes/Duration.cs @@ -0,0 +1,174 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/duration.proto +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace Google.Protobuf.WellKnownTypes { + + namespace Proto { + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public static partial class Duration { + + #region Descriptor + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static Duration() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "Ch5nb29nbGUvcHJvdG9idWYvZHVyYXRpb24ucHJvdG8SD2dvb2dsZS5wcm90", + "b2J1ZiIqCghEdXJhdGlvbhIPCgdzZWNvbmRzGAEgASgDEg0KBW5hbm9zGAIg", + "ASgFQlAKE2NvbS5nb29nbGUucHJvdG9idWZCDUR1cmF0aW9uUHJvdG9QAaAB", + "AaICA0dQQqoCHkdvb2dsZS5Qcm90b2J1Zi5XZWxsS25vd25UeXBlc2IGcHJv", + "dG8z")); + descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] { + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Duration), new[]{ "Seconds", "Nanos" }, null, null, null) + })); + } + #endregion + + } + } + #region Messages + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public sealed partial class Duration : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Duration()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.WellKnownTypes.Proto.Duration.Descriptor.MessageTypes[0]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public Duration() { + OnConstruction(); + } + + partial void OnConstruction(); + + public Duration(Duration other) : this() { + seconds_ = other.seconds_; + nanos_ = other.nanos_; + } + + public Duration Clone() { + return new Duration(this); + } + + public const int SecondsFieldNumber = 1; + private long seconds_; + public long Seconds { + get { return seconds_; } + set { + seconds_ = value; + } + } + + public const int NanosFieldNumber = 2; + private int nanos_; + public int Nanos { + get { return nanos_; } + set { + nanos_ = value; + } + } + + public override bool Equals(object other) { + return Equals(other as Duration); + } + + public bool Equals(Duration other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Seconds != other.Seconds) return false; + if (Nanos != other.Nanos) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (Seconds != 0L) hash ^= Seconds.GetHashCode(); + if (Nanos != 0) hash ^= Nanos.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (Seconds != 0L) { + output.WriteRawTag(8); + output.WriteInt64(Seconds); + } + if (Nanos != 0) { + output.WriteRawTag(16); + output.WriteInt32(Nanos); + } + } + + public int CalculateSize() { + int size = 0; + if (Seconds != 0L) { + size += 1 + pb::CodedOutputStream.ComputeInt64Size(Seconds); + } + if (Nanos != 0) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Nanos); + } + return size; + } + + public void MergeFrom(Duration other) { + if (other == null) { + return; + } + if (other.Seconds != 0L) { + Seconds = other.Seconds; + } + if (other.Nanos != 0) { + Nanos = other.Nanos; + } + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 8: { + Seconds = input.ReadInt64(); + break; + } + case 16: { + Nanos = input.ReadInt32(); + break; + } + } + } + } + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/DurationPartial.cs b/csharp/src/Google.Protobuf/WellKnownTypes/DurationPartial.cs new file mode 100644 index 0000000000000..18ebefd263e63 --- /dev/null +++ b/csharp/src/Google.Protobuf/WellKnownTypes/DurationPartial.cs @@ -0,0 +1,151 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using System; + +namespace Google.Protobuf.WellKnownTypes +{ + // Manually-written partial class for the Duration well-known type, + // providing a conversion to TimeSpan and convenience operators. + public partial class Duration + { + /// + /// The number of nanoseconds in a second. + /// + public const int NanosecondsPerSecond = 1000000000; + /// + /// The number of nanoseconds in a BCL tick (as used by and ). + /// + public const int NanosecondsPerTick = 100; + + /// + /// Converts this to a . + /// + /// If the duration is not a precise number of ticks, it is truncated towards 0. + /// The value of this duration, as a TimeSpan. + public TimeSpan ToTimeSpan() + { + checked + { + long ticks = Seconds * TimeSpan.TicksPerSecond + Nanos / NanosecondsPerTick; + return TimeSpan.FromTicks(ticks); + } + } + + /// + /// Converts the given to a . + /// + /// The TimeSpan to convert. + /// The value of the given TimeSpan, as a Duration. + public static Duration FromTimeSpan(TimeSpan timeSpan) + { + checked + { + long ticks = timeSpan.Ticks; + long seconds = ticks / TimeSpan.TicksPerSecond; + int nanos = (int) (ticks % TimeSpan.TicksPerSecond) * NanosecondsPerTick; + return new Duration { Seconds = seconds, Nanos = nanos }; + } + } + + /// + /// Returns the result of negating the duration. For example, the negation of 5 minutes is -5 minutes. + /// + /// The duration to negate. Must not be null. + /// The negated value of this duration. + public static Duration operator -(Duration value) + { + Preconditions.CheckNotNull(value, "value"); + checked + { + return Normalize(-value.Seconds, -value.Nanos); + } + } + + /// + /// Adds the two specified values together. + /// + /// The first value to add. Must not be null. + /// The second value to add. Must not be null. + /// + public static Duration operator +(Duration lhs, Duration rhs) + { + Preconditions.CheckNotNull(lhs, "lhs"); + Preconditions.CheckNotNull(rhs, "rhs"); + checked + { + return Normalize(lhs.Seconds + rhs.Seconds, lhs.Nanos + rhs.Nanos); + } + } + + /// + /// Subtracts one from another. + /// + /// The duration to subtract from. Must not be null. + /// The duration to subtract. Must not be null. + /// The difference between the two specified durations. + public static Duration operator -(Duration lhs, Duration rhs) + { + Preconditions.CheckNotNull(lhs, "lhs"); + Preconditions.CheckNotNull(rhs, "rhs"); + checked + { + return Normalize(lhs.Seconds - rhs.Seconds, lhs.Nanos - rhs.Nanos); + } + } + + /// + /// Creates a duration with the normalized values from the given number of seconds and + /// nanoseconds, conforming with the description in the proto file. + /// + internal static Duration Normalize(long seconds, int nanoseconds) + { + // Ensure that nanoseconds is in the range (-1,000,000,000, +1,000,000,000) + int extraSeconds = nanoseconds / NanosecondsPerSecond; + seconds += extraSeconds; + nanoseconds -= extraSeconds * NanosecondsPerSecond; + + // Now make sure that Sign(seconds) == Sign(nanoseconds) if Sign(seconds) != 0. + if (seconds < 0 && nanoseconds > 0) + { + seconds += 1; + nanoseconds -= NanosecondsPerSecond; + } + else if (seconds > 0 && nanoseconds < 0) + { + seconds -= 1; + nanoseconds += NanosecondsPerSecond; + } + return new Duration { Seconds = seconds, Nanos = nanoseconds }; + } + } +} diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Empty.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Empty.cs new file mode 100644 index 0000000000000..7d699c1d89ef4 --- /dev/null +++ b/csharp/src/Google.Protobuf/WellKnownTypes/Empty.cs @@ -0,0 +1,121 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/empty.proto +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace Google.Protobuf.WellKnownTypes { + + namespace Proto { + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public static partial class Empty { + + #region Descriptor + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static Empty() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "Chtnb29nbGUvcHJvdG9idWYvZW1wdHkucHJvdG8SD2dvb2dsZS5wcm90b2J1", + "ZiIHCgVFbXB0eUJKChNjb20uZ29vZ2xlLnByb3RvYnVmQgpFbXB0eVByb3Rv", + "UAGiAgNHUEKqAh5Hb29nbGUuUHJvdG9idWYuV2VsbEtub3duVHlwZXNiBnBy", + "b3RvMw==")); + descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] { + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Empty), null, null, null, null) + })); + } + #endregion + + } + } + #region Messages + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public sealed partial class Empty : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Empty()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.WellKnownTypes.Proto.Empty.Descriptor.MessageTypes[0]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public Empty() { + OnConstruction(); + } + + partial void OnConstruction(); + + public Empty(Empty other) : this() { + } + + public Empty Clone() { + return new Empty(this); + } + + public override bool Equals(object other) { + return Equals(other as Empty); + } + + public bool Equals(Empty other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + return true; + } + + public override int GetHashCode() { + int hash = 1; + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + } + + public int CalculateSize() { + int size = 0; + return size; + } + + public void MergeFrom(Empty other) { + if (other == null) { + return; + } + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + } + } + } + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs b/csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs new file mode 100644 index 0000000000000..0dac4403b4f43 --- /dev/null +++ b/csharp/src/Google.Protobuf/WellKnownTypes/FieldMask.cs @@ -0,0 +1,139 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/field_mask.proto +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace Google.Protobuf.WellKnownTypes { + + namespace Proto { + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public static partial class FieldMask { + + #region Descriptor + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static FieldMask() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "CiBnb29nbGUvcHJvdG9idWYvZmllbGRfbWFzay5wcm90bxIPZ29vZ2xlLnBy", + "b3RvYnVmIhoKCUZpZWxkTWFzaxINCgVwYXRocxgBIAMoCUJOChNjb20uZ29v", + "Z2xlLnByb3RvYnVmQg5GaWVsZE1hc2tQcm90b1ABogIDR1BCqgIeR29vZ2xl", + "LlByb3RvYnVmLldlbGxLbm93blR5cGVzYgZwcm90bzM=")); + descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] { + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.WellKnownTypes.FieldMask), new[]{ "Paths" }, null, null, null) + })); + } + #endregion + + } + } + #region Messages + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public sealed partial class FieldMask : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new FieldMask()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.WellKnownTypes.Proto.FieldMask.Descriptor.MessageTypes[0]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public FieldMask() { + OnConstruction(); + } + + partial void OnConstruction(); + + public FieldMask(FieldMask other) : this() { + paths_ = other.paths_.Clone(); + } + + public FieldMask Clone() { + return new FieldMask(this); + } + + public const int PathsFieldNumber = 1; + private static readonly pb::FieldCodec _repeated_paths_codec + = pb::FieldCodec.ForString(10); + private readonly pbc::RepeatedField paths_ = new pbc::RepeatedField(); + public pbc::RepeatedField Paths { + get { return paths_; } + } + + public override bool Equals(object other) { + return Equals(other as FieldMask); + } + + public bool Equals(FieldMask other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if(!paths_.Equals(other.paths_)) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + hash ^= paths_.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + paths_.WriteTo(output, _repeated_paths_codec); + } + + public int CalculateSize() { + int size = 0; + size += paths_.CalculateSize(_repeated_paths_codec); + return size; + } + + public void MergeFrom(FieldMask other) { + if (other == null) { + return; + } + paths_.Add(other.paths_); + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 10: { + paths_.AddEntriesFrom(input, _repeated_paths_codec); + break; + } + } + } + } + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/SourceContext.cs b/csharp/src/Google.Protobuf/WellKnownTypes/SourceContext.cs new file mode 100644 index 0000000000000..8347999df1ece --- /dev/null +++ b/csharp/src/Google.Protobuf/WellKnownTypes/SourceContext.cs @@ -0,0 +1,148 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/source_context.proto +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace Google.Protobuf.WellKnownTypes { + + namespace Proto { + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public static partial class SourceContext { + + #region Descriptor + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static SourceContext() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "CiRnb29nbGUvcHJvdG9idWYvc291cmNlX2NvbnRleHQucHJvdG8SD2dvb2ds", + "ZS5wcm90b2J1ZiIiCg1Tb3VyY2VDb250ZXh0EhEKCWZpbGVfbmFtZRgBIAEo", + "CUJSChNjb20uZ29vZ2xlLnByb3RvYnVmQhJTb3VyY2VDb250ZXh0UHJvdG9Q", + "AaICA0dQQqoCHkdvb2dsZS5Qcm90b2J1Zi5XZWxsS25vd25UeXBlc2IGcHJv", + "dG8z")); + descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] { + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.WellKnownTypes.SourceContext), new[]{ "FileName" }, null, null, null) + })); + } + #endregion + + } + } + #region Messages + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public sealed partial class SourceContext : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new SourceContext()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.WellKnownTypes.Proto.SourceContext.Descriptor.MessageTypes[0]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public SourceContext() { + OnConstruction(); + } + + partial void OnConstruction(); + + public SourceContext(SourceContext other) : this() { + fileName_ = other.fileName_; + } + + public SourceContext Clone() { + return new SourceContext(this); + } + + public const int FileNameFieldNumber = 1; + private string fileName_ = ""; + public string FileName { + get { return fileName_; } + set { + fileName_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public override bool Equals(object other) { + return Equals(other as SourceContext); + } + + public bool Equals(SourceContext other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (FileName != other.FileName) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (FileName.Length != 0) hash ^= FileName.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (FileName.Length != 0) { + output.WriteRawTag(10); + output.WriteString(FileName); + } + } + + public int CalculateSize() { + int size = 0; + if (FileName.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(FileName); + } + return size; + } + + public void MergeFrom(SourceContext other) { + if (other == null) { + return; + } + if (other.FileName.Length != 0) { + FileName = other.FileName; + } + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 10: { + FileName = input.ReadString(); + break; + } + } + } + } + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Struct.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Struct.cs new file mode 100644 index 0000000000000..1e8a8236b160e --- /dev/null +++ b/csharp/src/Google.Protobuf/WellKnownTypes/Struct.cs @@ -0,0 +1,533 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/struct.proto +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace Google.Protobuf.WellKnownTypes { + + namespace Proto { + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public static partial class Struct { + + #region Descriptor + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static Struct() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "Chxnb29nbGUvcHJvdG9idWYvc3RydWN0LnByb3RvEg9nb29nbGUucHJvdG9i", + "dWYihAEKBlN0cnVjdBIzCgZmaWVsZHMYASADKAsyIy5nb29nbGUucHJvdG9i", + "dWYuU3RydWN0LkZpZWxkc0VudHJ5GkUKC0ZpZWxkc0VudHJ5EgsKA2tleRgB", + "IAEoCRIlCgV2YWx1ZRgCIAEoCzIWLmdvb2dsZS5wcm90b2J1Zi5WYWx1ZToC", + "OAEi6gEKBVZhbHVlEjAKCm51bGxfdmFsdWUYASABKA4yGi5nb29nbGUucHJv", + "dG9idWYuTnVsbFZhbHVlSAASFgoMbnVtYmVyX3ZhbHVlGAIgASgBSAASFgoM", + "c3RyaW5nX3ZhbHVlGAMgASgJSAASFAoKYm9vbF92YWx1ZRgEIAEoCEgAEi8K", + "DHN0cnVjdF92YWx1ZRgFIAEoCzIXLmdvb2dsZS5wcm90b2J1Zi5TdHJ1Y3RI", + "ABIwCgpsaXN0X3ZhbHVlGAYgASgLMhouZ29vZ2xlLnByb3RvYnVmLkxpc3RW", + "YWx1ZUgAQgYKBGtpbmQiMwoJTGlzdFZhbHVlEiYKBnZhbHVlcxgBIAMoCzIW", + "Lmdvb2dsZS5wcm90b2J1Zi5WYWx1ZSobCglOdWxsVmFsdWUSDgoKTlVMTF9W", + "QUxVRRAAQk4KE2NvbS5nb29nbGUucHJvdG9idWZCC1N0cnVjdFByb3RvUAGg", + "AQGiAgNHUEKqAh5Hb29nbGUuUHJvdG9idWYuV2VsbEtub3duVHlwZXNiBnBy", + "b3RvMw==")); + descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedCodeInfo(new[] {typeof(global::Google.Protobuf.WellKnownTypes.NullValue), }, new pbr::GeneratedCodeInfo[] { + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Struct), new[]{ "Fields" }, null, null, new pbr::GeneratedCodeInfo[] { null, }), + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Value), new[]{ "NullValue", "NumberValue", "StringValue", "BoolValue", "StructValue", "ListValue" }, new[]{ "Kind" }, null, null), + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.WellKnownTypes.ListValue), new[]{ "Values" }, null, null, null) + })); + } + #endregion + + } + } + #region Enums + public enum NullValue { + NULL_VALUE = 0, + } + + #endregion + + #region Messages + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public sealed partial class Struct : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Struct()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.WellKnownTypes.Proto.Struct.Descriptor.MessageTypes[0]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public Struct() { + OnConstruction(); + } + + partial void OnConstruction(); + + public Struct(Struct other) : this() { + fields_ = other.fields_.Clone(); + } + + public Struct Clone() { + return new Struct(this); + } + + public const int FieldsFieldNumber = 1; + private static readonly pbc::MapField.Codec _map_fields_codec + = new pbc::MapField.Codec(pb::FieldCodec.ForString(10), pb::FieldCodec.ForMessage(18, global::Google.Protobuf.WellKnownTypes.Value.Parser), 10); + private readonly pbc::MapField fields_ = new pbc::MapField(); + public pbc::MapField Fields { + get { return fields_; } + } + + public override bool Equals(object other) { + return Equals(other as Struct); + } + + public bool Equals(Struct other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (!Fields.Equals(other.Fields)) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + hash ^= Fields.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + fields_.WriteTo(output, _map_fields_codec); + } + + public int CalculateSize() { + int size = 0; + size += fields_.CalculateSize(_map_fields_codec); + return size; + } + + public void MergeFrom(Struct other) { + if (other == null) { + return; + } + fields_.Add(other.fields_); + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 10: { + fields_.AddEntriesFrom(input, _map_fields_codec); + break; + } + } + } + } + + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public sealed partial class Value : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Value()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.WellKnownTypes.Proto.Struct.Descriptor.MessageTypes[1]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public Value() { + OnConstruction(); + } + + partial void OnConstruction(); + + public Value(Value other) : this() { + switch (other.KindCase) { + case KindOneofCase.NullValue: + NullValue = other.NullValue; + break; + case KindOneofCase.NumberValue: + NumberValue = other.NumberValue; + break; + case KindOneofCase.StringValue: + StringValue = other.StringValue; + break; + case KindOneofCase.BoolValue: + BoolValue = other.BoolValue; + break; + case KindOneofCase.StructValue: + StructValue = other.StructValue.Clone(); + break; + case KindOneofCase.ListValue: + ListValue = other.ListValue.Clone(); + break; + } + + } + + public Value Clone() { + return new Value(this); + } + + public const int NullValueFieldNumber = 1; + public global::Google.Protobuf.WellKnownTypes.NullValue NullValue { + get { return kindCase_ == KindOneofCase.NullValue ? (global::Google.Protobuf.WellKnownTypes.NullValue) kind_ : global::Google.Protobuf.WellKnownTypes.NullValue.NULL_VALUE; } + set { + kind_ = value; + kindCase_ = KindOneofCase.NullValue; + } + } + + public const int NumberValueFieldNumber = 2; + public double NumberValue { + get { return kindCase_ == KindOneofCase.NumberValue ? (double) kind_ : 0D; } + set { + kind_ = value; + kindCase_ = KindOneofCase.NumberValue; + } + } + + public const int StringValueFieldNumber = 3; + public string StringValue { + get { return kindCase_ == KindOneofCase.StringValue ? (string) kind_ : ""; } + set { + kind_ = pb::Preconditions.CheckNotNull(value, "value"); + kindCase_ = KindOneofCase.StringValue; + } + } + + public const int BoolValueFieldNumber = 4; + public bool BoolValue { + get { return kindCase_ == KindOneofCase.BoolValue ? (bool) kind_ : false; } + set { + kind_ = value; + kindCase_ = KindOneofCase.BoolValue; + } + } + + public const int StructValueFieldNumber = 5; + public global::Google.Protobuf.WellKnownTypes.Struct StructValue { + get { return kindCase_ == KindOneofCase.StructValue ? (global::Google.Protobuf.WellKnownTypes.Struct) kind_ : null; } + set { + kind_ = value; + kindCase_ = value == null ? KindOneofCase.None : KindOneofCase.StructValue; + } + } + + public const int ListValueFieldNumber = 6; + public global::Google.Protobuf.WellKnownTypes.ListValue ListValue { + get { return kindCase_ == KindOneofCase.ListValue ? (global::Google.Protobuf.WellKnownTypes.ListValue) kind_ : null; } + set { + kind_ = value; + kindCase_ = value == null ? KindOneofCase.None : KindOneofCase.ListValue; + } + } + + private object kind_; + public enum KindOneofCase { + None = 0, + NullValue = 1, + NumberValue = 2, + StringValue = 3, + BoolValue = 4, + StructValue = 5, + ListValue = 6, + } + private KindOneofCase kindCase_ = KindOneofCase.None; + public KindOneofCase KindCase { + get { return kindCase_; } + } + + public void ClearKind() { + kindCase_ = KindOneofCase.None; + kind_ = null; + } + + public override bool Equals(object other) { + return Equals(other as Value); + } + + public bool Equals(Value other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (NullValue != other.NullValue) return false; + if (NumberValue != other.NumberValue) return false; + if (StringValue != other.StringValue) return false; + if (BoolValue != other.BoolValue) return false; + if (!object.Equals(StructValue, other.StructValue)) return false; + if (!object.Equals(ListValue, other.ListValue)) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (kindCase_ == KindOneofCase.NullValue) hash ^= NullValue.GetHashCode(); + if (kindCase_ == KindOneofCase.NumberValue) hash ^= NumberValue.GetHashCode(); + if (kindCase_ == KindOneofCase.StringValue) hash ^= StringValue.GetHashCode(); + if (kindCase_ == KindOneofCase.BoolValue) hash ^= BoolValue.GetHashCode(); + if (kindCase_ == KindOneofCase.StructValue) hash ^= StructValue.GetHashCode(); + if (kindCase_ == KindOneofCase.ListValue) hash ^= ListValue.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (kindCase_ == KindOneofCase.NullValue) { + output.WriteRawTag(8); + output.WriteEnum((int) NullValue); + } + if (kindCase_ == KindOneofCase.NumberValue) { + output.WriteRawTag(17); + output.WriteDouble(NumberValue); + } + if (kindCase_ == KindOneofCase.StringValue) { + output.WriteRawTag(26); + output.WriteString(StringValue); + } + if (kindCase_ == KindOneofCase.BoolValue) { + output.WriteRawTag(32); + output.WriteBool(BoolValue); + } + if (kindCase_ == KindOneofCase.StructValue) { + output.WriteRawTag(42); + output.WriteMessage(StructValue); + } + if (kindCase_ == KindOneofCase.ListValue) { + output.WriteRawTag(50); + output.WriteMessage(ListValue); + } + } + + public int CalculateSize() { + int size = 0; + if (kindCase_ == KindOneofCase.NullValue) { + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) NullValue); + } + if (kindCase_ == KindOneofCase.NumberValue) { + size += 1 + 8; + } + if (kindCase_ == KindOneofCase.StringValue) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(StringValue); + } + if (kindCase_ == KindOneofCase.BoolValue) { + size += 1 + 1; + } + if (kindCase_ == KindOneofCase.StructValue) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(StructValue); + } + if (kindCase_ == KindOneofCase.ListValue) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(ListValue); + } + return size; + } + + public void MergeFrom(Value other) { + if (other == null) { + return; + } + switch (other.KindCase) { + case KindOneofCase.NullValue: + NullValue = other.NullValue; + break; + case KindOneofCase.NumberValue: + NumberValue = other.NumberValue; + break; + case KindOneofCase.StringValue: + StringValue = other.StringValue; + break; + case KindOneofCase.BoolValue: + BoolValue = other.BoolValue; + break; + case KindOneofCase.StructValue: + StructValue = other.StructValue; + break; + case KindOneofCase.ListValue: + ListValue = other.ListValue; + break; + } + + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 8: { + kind_ = input.ReadEnum(); + kindCase_ = KindOneofCase.NullValue; + break; + } + case 17: { + NumberValue = input.ReadDouble(); + break; + } + case 26: { + StringValue = input.ReadString(); + break; + } + case 32: { + BoolValue = input.ReadBool(); + break; + } + case 42: { + global::Google.Protobuf.WellKnownTypes.Struct subBuilder = new global::Google.Protobuf.WellKnownTypes.Struct(); + if (kindCase_ == KindOneofCase.StructValue) { + subBuilder.MergeFrom(StructValue); + } + input.ReadMessage(subBuilder); + StructValue = subBuilder; + break; + } + case 50: { + global::Google.Protobuf.WellKnownTypes.ListValue subBuilder = new global::Google.Protobuf.WellKnownTypes.ListValue(); + if (kindCase_ == KindOneofCase.ListValue) { + subBuilder.MergeFrom(ListValue); + } + input.ReadMessage(subBuilder); + ListValue = subBuilder; + break; + } + } + } + } + + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public sealed partial class ListValue : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new ListValue()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.WellKnownTypes.Proto.Struct.Descriptor.MessageTypes[2]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public ListValue() { + OnConstruction(); + } + + partial void OnConstruction(); + + public ListValue(ListValue other) : this() { + values_ = other.values_.Clone(); + } + + public ListValue Clone() { + return new ListValue(this); + } + + public const int ValuesFieldNumber = 1; + private static readonly pb::FieldCodec _repeated_values_codec + = pb::FieldCodec.ForMessage(10, global::Google.Protobuf.WellKnownTypes.Value.Parser); + private readonly pbc::RepeatedField values_ = new pbc::RepeatedField(); + public pbc::RepeatedField Values { + get { return values_; } + } + + public override bool Equals(object other) { + return Equals(other as ListValue); + } + + public bool Equals(ListValue other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if(!values_.Equals(other.values_)) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + hash ^= values_.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + values_.WriteTo(output, _repeated_values_codec); + } + + public int CalculateSize() { + int size = 0; + size += values_.CalculateSize(_repeated_values_codec); + return size; + } + + public void MergeFrom(ListValue other) { + if (other == null) { + return; + } + values_.Add(other.values_); + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 10: { + values_.AddEntriesFrom(input, _repeated_values_codec); + break; + } + } + } + } + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/TimeExtensions.cs b/csharp/src/Google.Protobuf/WellKnownTypes/TimeExtensions.cs new file mode 100644 index 0000000000000..dd485d324aa12 --- /dev/null +++ b/csharp/src/Google.Protobuf/WellKnownTypes/TimeExtensions.cs @@ -0,0 +1,80 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Google.Protobuf.WellKnownTypes +{ + /// + /// Extension methods on BCL time-related types, converting to protobuf types. + /// + public static class TimeExtensions + { + /// + /// Converts the given to a . + /// + /// The date and time to convert to a timestamp. + /// The value has a other than Utc. + /// The converted timestamp. + public static Timestamp ToTimestamp(this DateTime dateTime) + { + return Timestamp.FromDateTime(dateTime); + } + + /// + /// Converts the given to a + /// + /// The offset is taken into consideration when converting the value (so the same instant in time + /// is represented) but is not a separate part of the resulting value. In other words, there is no + /// roundtrip operation to retrieve the original DateTimeOffset. + /// The date and time (with UTC offset) to convert to a timestamp. + /// The converted timestamp. + public static Timestamp ToTimestamp(this DateTimeOffset dateTimeOffset) + { + return Timestamp.FromDateTimeOffset(dateTimeOffset); + } + + /// + /// Converts the given to a . + /// + /// The time span to convert. + /// The converted duration. + public static Duration ToDuration(this TimeSpan timeSpan) + { + return Duration.FromTimeSpan(timeSpan); + } + } +} diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs new file mode 100644 index 0000000000000..d7c0954f4a9f8 --- /dev/null +++ b/csharp/src/Google.Protobuf/WellKnownTypes/Timestamp.cs @@ -0,0 +1,174 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/timestamp.proto +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace Google.Protobuf.WellKnownTypes { + + namespace Proto { + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public static partial class Timestamp { + + #region Descriptor + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static Timestamp() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "Ch9nb29nbGUvcHJvdG9idWYvdGltZXN0YW1wLnByb3RvEg9nb29nbGUucHJv", + "dG9idWYiKwoJVGltZXN0YW1wEg8KB3NlY29uZHMYASABKAMSDQoFbmFub3MY", + "AiABKAVCUQoTY29tLmdvb2dsZS5wcm90b2J1ZkIOVGltZXN0YW1wUHJvdG9Q", + "AaABAaICA0dQQqoCHkdvb2dsZS5Qcm90b2J1Zi5XZWxsS25vd25UeXBlc2IG", + "cHJvdG8z")); + descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, + new pbr::FileDescriptor[] { }, + new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] { + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Timestamp), new[]{ "Seconds", "Nanos" }, null, null, null) + })); + } + #endregion + + } + } + #region Messages + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public sealed partial class Timestamp : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Timestamp()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.WellKnownTypes.Proto.Timestamp.Descriptor.MessageTypes[0]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public Timestamp() { + OnConstruction(); + } + + partial void OnConstruction(); + + public Timestamp(Timestamp other) : this() { + seconds_ = other.seconds_; + nanos_ = other.nanos_; + } + + public Timestamp Clone() { + return new Timestamp(this); + } + + public const int SecondsFieldNumber = 1; + private long seconds_; + public long Seconds { + get { return seconds_; } + set { + seconds_ = value; + } + } + + public const int NanosFieldNumber = 2; + private int nanos_; + public int Nanos { + get { return nanos_; } + set { + nanos_ = value; + } + } + + public override bool Equals(object other) { + return Equals(other as Timestamp); + } + + public bool Equals(Timestamp other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Seconds != other.Seconds) return false; + if (Nanos != other.Nanos) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (Seconds != 0L) hash ^= Seconds.GetHashCode(); + if (Nanos != 0) hash ^= Nanos.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (Seconds != 0L) { + output.WriteRawTag(8); + output.WriteInt64(Seconds); + } + if (Nanos != 0) { + output.WriteRawTag(16); + output.WriteInt32(Nanos); + } + } + + public int CalculateSize() { + int size = 0; + if (Seconds != 0L) { + size += 1 + pb::CodedOutputStream.ComputeInt64Size(Seconds); + } + if (Nanos != 0) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Nanos); + } + return size; + } + + public void MergeFrom(Timestamp other) { + if (other == null) { + return; + } + if (other.Seconds != 0L) { + Seconds = other.Seconds; + } + if (other.Nanos != 0) { + Nanos = other.Nanos; + } + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 8: { + Seconds = input.ReadInt64(); + break; + } + case 16: { + Nanos = input.ReadInt32(); + break; + } + } + } + } + + } + + #endregion + +} + +#endregion Designer generated code diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/TimestampPartial.cs b/csharp/src/Google.Protobuf/WellKnownTypes/TimestampPartial.cs new file mode 100644 index 0000000000000..6858435820dc7 --- /dev/null +++ b/csharp/src/Google.Protobuf/WellKnownTypes/TimestampPartial.cs @@ -0,0 +1,167 @@ +#region Copyright notice and license +// Protocol Buffers - Google's data interchange format +// Copyright 2015 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. +#endregion + +using System; + +namespace Google.Protobuf.WellKnownTypes +{ + public partial class Timestamp + { + private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + private static readonly long BclSecondsAtUnixEpoch = UnixEpoch.Ticks / TimeSpan.TicksPerSecond; + + /// + /// Returns the difference between one and another, as a . + /// + /// The timestamp to subtract from. Must not be null. + /// The timestamp to subtract. Must not be null. + /// The difference between the two specified timestamps. + public static Duration operator -(Timestamp lhs, Timestamp rhs) + { + Preconditions.CheckNotNull(lhs, "lhs"); + Preconditions.CheckNotNull(rhs, "rhs"); + checked + { + return Duration.Normalize(lhs.Seconds - rhs.Seconds, lhs.Nanos - rhs.Nanos); + } + } + + /// + /// Adds a to a , to obtain another Timestamp. + /// + /// The timestamp to add the duration to. Must not be null. + /// The duration to add. Must not be null. + /// The result of adding the duration to the timestamp. + public static Timestamp operator +(Timestamp lhs, Duration rhs) + { + Preconditions.CheckNotNull(lhs, "lhs"); + Preconditions.CheckNotNull(rhs, "rhs"); + checked + { + return Normalize(lhs.Seconds + rhs.Seconds, lhs.Nanos + rhs.Nanos); + } + } + + /// + /// Subtracts a from a , to obtain another Timestamp. + /// + /// The timestamp to subtract the duration from. Must not be null. + /// The duration to subtract. + /// The result of subtracting the duration from the timestamp. + public static Timestamp operator -(Timestamp lhs, Duration rhs) + { + Preconditions.CheckNotNull(lhs, "lhs"); + Preconditions.CheckNotNull(rhs, "rhs"); + checked + { + return Normalize(lhs.Seconds - rhs.Seconds, lhs.Nanos - rhs.Nanos); + } + } + + /// + /// Converts this timestamp into a . + /// + /// + /// The resulting DateTime will always have a Kind of Utc. + /// If the timestamp is not a precise number of ticks, it will be truncated towards the start + /// of time. For example, a timestamp with a value of 99 will result in a + /// value precisely on a second. + /// + /// This timestamp as a DateTime. + public DateTime ToDateTime() + { + return UnixEpoch.AddSeconds(Seconds).AddTicks(Nanos / Duration.NanosecondsPerTick); + } + + /// + /// Converts this timestamp into a . + /// + /// + /// The resulting DateTimeOffset will always have an Offset of zero. + /// If the timestamp is not a precise number of ticks, it will be truncated towards the start + /// of time. For example, a timestamp with a value of 99 will result in a + /// value precisely on a second. + /// + /// This timestamp as a DateTimeOffset. + public DateTimeOffset ToDateTimeOffset() + { + return new DateTimeOffset(ToDateTime(), TimeSpan.Zero); + } + + /// + /// Converts the specified to a . + /// + /// + /// The Kind of is not DateTimeKind.Utc. + /// The converted timestamp. + public static Timestamp FromDateTime(DateTime dateTime) + { + if (dateTime.Kind != DateTimeKind.Utc) + { + throw new ArgumentException("Conversion from DateTime to Timestamp requires the DateTime kind to be Utc", "dateTime"); + } + // Do the arithmetic using DateTime.Ticks, which is always non-negative, making things simpler. + long secondsSinceBclEpoch = dateTime.Ticks / TimeSpan.TicksPerSecond; + int nanoseconds = (int) (dateTime.Ticks % TimeSpan.TicksPerSecond) * Duration.NanosecondsPerTick; + return new Timestamp { Seconds = secondsSinceBclEpoch - BclSecondsAtUnixEpoch, Nanos = nanoseconds }; + } + + /// + /// Converts the given to a + /// + /// The offset is taken into consideration when converting the value (so the same instant in time + /// is represented) but is not a separate part of the resulting value. In other words, there is no + /// roundtrip operation to retrieve the original DateTimeOffset. + /// The date and time (with UTC offset) to convert to a timestamp. + /// The converted timestamp. + public static Timestamp FromDateTimeOffset(DateTimeOffset dateTimeOffset) + { + // We don't need to worry about this having negative ticks: DateTimeOffset is constrained to handle + // values whose *UTC* value is in the range of DateTime. + return FromDateTime(dateTimeOffset.UtcDateTime); + } + + internal static Timestamp Normalize(long seconds, int nanoseconds) + { + int extraSeconds = nanoseconds / Duration.NanosecondsPerSecond; + seconds += extraSeconds; + nanoseconds -= extraSeconds * Duration.NanosecondsPerSecond; + + if (nanoseconds < 0) + { + nanoseconds += Duration.NanosecondsPerSecond; + seconds--; + } + return new Timestamp { Seconds = seconds, Nanos = nanoseconds }; + } + } +} diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/Type.cs b/csharp/src/Google.Protobuf/WellKnownTypes/Type.cs new file mode 100644 index 0000000000000..ff2ecc579cc16 --- /dev/null +++ b/csharp/src/Google.Protobuf/WellKnownTypes/Type.cs @@ -0,0 +1,1024 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: google/protobuf/type.proto +#pragma warning disable 1591, 0612, 3021 +#region Designer generated code + +using pb = global::Google.Protobuf; +using pbc = global::Google.Protobuf.Collections; +using pbr = global::Google.Protobuf.Reflection; +using scg = global::System.Collections.Generic; +namespace Google.Protobuf.WellKnownTypes { + + namespace Proto { + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public static partial class Type { + + #region Descriptor + public static pbr::FileDescriptor Descriptor { + get { return descriptor; } + } + private static pbr::FileDescriptor descriptor; + + static Type() { + byte[] descriptorData = global::System.Convert.FromBase64String( + string.Concat( + "Chpnb29nbGUvcHJvdG9idWYvdHlwZS5wcm90bxIPZ29vZ2xlLnByb3RvYnVm", + "Ghlnb29nbGUvcHJvdG9idWYvYW55LnByb3RvGiRnb29nbGUvcHJvdG9idWYv", + "c291cmNlX2NvbnRleHQucHJvdG8irgEKBFR5cGUSDAoEbmFtZRgBIAEoCRIm", + "CgZmaWVsZHMYAiADKAsyFi5nb29nbGUucHJvdG9idWYuRmllbGQSDgoGb25l", + "b2ZzGAMgAygJEigKB29wdGlvbnMYBCADKAsyFy5nb29nbGUucHJvdG9idWYu", + "T3B0aW9uEjYKDnNvdXJjZV9jb250ZXh0GAUgASgLMh4uZ29vZ2xlLnByb3Rv", + "YnVmLlNvdXJjZUNvbnRleHQimwUKBUZpZWxkEikKBGtpbmQYASABKA4yGy5n", + "b29nbGUucHJvdG9idWYuRmllbGQuS2luZBI3CgtjYXJkaW5hbGl0eRgCIAEo", + "DjIiLmdvb2dsZS5wcm90b2J1Zi5GaWVsZC5DYXJkaW5hbGl0eRIOCgZudW1i", + "ZXIYAyABKAUSDAoEbmFtZRgEIAEoCRIQCgh0eXBlX3VybBgGIAEoCRITCgtv", + "bmVvZl9pbmRleBgHIAEoBRIOCgZwYWNrZWQYCCABKAgSKAoHb3B0aW9ucxgJ", + "IAMoCzIXLmdvb2dsZS5wcm90b2J1Zi5PcHRpb24iuAIKBEtpbmQSEAoMVFlQ", + "RV9VTktOT1dOEAASDwoLVFlQRV9ET1VCTEUQARIOCgpUWVBFX0ZMT0FUEAIS", + "DgoKVFlQRV9JTlQ2NBADEg8KC1RZUEVfVUlOVDY0EAQSDgoKVFlQRV9JTlQz", + "MhAFEhAKDFRZUEVfRklYRUQ2NBAGEhAKDFRZUEVfRklYRUQzMhAHEg0KCVRZ", + "UEVfQk9PTBAIEg8KC1RZUEVfU1RSSU5HEAkSEAoMVFlQRV9NRVNTQUdFEAsS", + "DgoKVFlQRV9CWVRFUxAMEg8KC1RZUEVfVUlOVDMyEA0SDQoJVFlQRV9FTlVN", + "EA4SEQoNVFlQRV9TRklYRUQzMhAPEhEKDVRZUEVfU0ZJWEVENjQQEBIPCgtU", + "WVBFX1NJTlQzMhAREg8KC1RZUEVfU0lOVDY0EBIidAoLQ2FyZGluYWxpdHkS", + "FwoTQ0FSRElOQUxJVFlfVU5LTk9XThAAEhgKFENBUkRJTkFMSVRZX09QVElP", + "TkFMEAESGAoUQ0FSRElOQUxJVFlfUkVRVUlSRUQQAhIYChRDQVJESU5BTElU", + "WV9SRVBFQVRFRBADIqUBCgRFbnVtEgwKBG5hbWUYASABKAkSLQoJZW51bXZh", + "bHVlGAIgAygLMhouZ29vZ2xlLnByb3RvYnVmLkVudW1WYWx1ZRIoCgdvcHRp", + "b25zGAMgAygLMhcuZ29vZ2xlLnByb3RvYnVmLk9wdGlvbhI2Cg5zb3VyY2Vf", + "Y29udGV4dBgEIAEoCzIeLmdvb2dsZS5wcm90b2J1Zi5Tb3VyY2VDb250ZXh0", + "IlMKCUVudW1WYWx1ZRIMCgRuYW1lGAEgASgJEg4KBm51bWJlchgCIAEoBRIo", + "CgdvcHRpb25zGAMgAygLMhcuZ29vZ2xlLnByb3RvYnVmLk9wdGlvbiI7CgZP", + "cHRpb24SDAoEbmFtZRgBIAEoCRIjCgV2YWx1ZRgCIAEoCzIULmdvb2dsZS5w", + "cm90b2J1Zi5BbnlCSQoTY29tLmdvb2dsZS5wcm90b2J1ZkIJVHlwZVByb3Rv", + "UAGiAgNHUEKqAh5Hb29nbGUuUHJvdG9idWYuV2VsbEtub3duVHlwZXNiBnBy", + "b3RvMw==")); + descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, + new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.Proto.Any.Descriptor, global::Google.Protobuf.WellKnownTypes.Proto.SourceContext.Descriptor, }, + new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] { + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Type), new[]{ "Name", "Fields", "Oneofs", "Options", "SourceContext" }, null, null, null), + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Field), new[]{ "Kind", "Cardinality", "Number", "Name", "TypeUrl", "OneofIndex", "Packed", "Options" }, null, new[]{ typeof(global::Google.Protobuf.WellKnownTypes.Field.Types.Kind), typeof(global::Google.Protobuf.WellKnownTypes.Field.Types.Cardinality) }, null), + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Enum), new[]{ "Name", "Enumvalue", "Options", "SourceContext" }, null, null, null), + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.WellKnownTypes.EnumValue), new[]{ "Name", "Number", "Options" }, null, null, null), + new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.WellKnownTypes.Option), new[]{ "Name", "Value" }, null, null, null) + })); + } + #endregion + + } + } + #region Messages + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public sealed partial class Type : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Type()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.WellKnownTypes.Proto.Type.Descriptor.MessageTypes[0]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public Type() { + OnConstruction(); + } + + partial void OnConstruction(); + + public Type(Type other) : this() { + name_ = other.name_; + fields_ = other.fields_.Clone(); + oneofs_ = other.oneofs_.Clone(); + options_ = other.options_.Clone(); + SourceContext = other.sourceContext_ != null ? other.SourceContext.Clone() : null; + } + + public Type Clone() { + return new Type(this); + } + + public const int NameFieldNumber = 1; + private string name_ = ""; + public string Name { + get { return name_; } + set { + name_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int FieldsFieldNumber = 2; + private static readonly pb::FieldCodec _repeated_fields_codec + = pb::FieldCodec.ForMessage(18, global::Google.Protobuf.WellKnownTypes.Field.Parser); + private readonly pbc::RepeatedField fields_ = new pbc::RepeatedField(); + public pbc::RepeatedField Fields { + get { return fields_; } + } + + public const int OneofsFieldNumber = 3; + private static readonly pb::FieldCodec _repeated_oneofs_codec + = pb::FieldCodec.ForString(26); + private readonly pbc::RepeatedField oneofs_ = new pbc::RepeatedField(); + public pbc::RepeatedField Oneofs { + get { return oneofs_; } + } + + public const int OptionsFieldNumber = 4; + private static readonly pb::FieldCodec _repeated_options_codec + = pb::FieldCodec.ForMessage(34, global::Google.Protobuf.WellKnownTypes.Option.Parser); + private readonly pbc::RepeatedField options_ = new pbc::RepeatedField(); + public pbc::RepeatedField Options { + get { return options_; } + } + + public const int SourceContextFieldNumber = 5; + private global::Google.Protobuf.WellKnownTypes.SourceContext sourceContext_; + public global::Google.Protobuf.WellKnownTypes.SourceContext SourceContext { + get { return sourceContext_; } + set { + sourceContext_ = value; + } + } + + public override bool Equals(object other) { + return Equals(other as Type); + } + + public bool Equals(Type other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Name != other.Name) return false; + if(!fields_.Equals(other.fields_)) return false; + if(!oneofs_.Equals(other.oneofs_)) return false; + if(!options_.Equals(other.options_)) return false; + if (!object.Equals(SourceContext, other.SourceContext)) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (Name.Length != 0) hash ^= Name.GetHashCode(); + hash ^= fields_.GetHashCode(); + hash ^= oneofs_.GetHashCode(); + hash ^= options_.GetHashCode(); + if (sourceContext_ != null) hash ^= SourceContext.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (Name.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Name); + } + fields_.WriteTo(output, _repeated_fields_codec); + oneofs_.WriteTo(output, _repeated_oneofs_codec); + options_.WriteTo(output, _repeated_options_codec); + if (sourceContext_ != null) { + output.WriteRawTag(42); + output.WriteMessage(SourceContext); + } + } + + public int CalculateSize() { + int size = 0; + if (Name.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); + } + size += fields_.CalculateSize(_repeated_fields_codec); + size += oneofs_.CalculateSize(_repeated_oneofs_codec); + size += options_.CalculateSize(_repeated_options_codec); + if (sourceContext_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(SourceContext); + } + return size; + } + + public void MergeFrom(Type other) { + if (other == null) { + return; + } + if (other.Name.Length != 0) { + Name = other.Name; + } + fields_.Add(other.fields_); + oneofs_.Add(other.oneofs_); + options_.Add(other.options_); + if (other.sourceContext_ != null) { + if (sourceContext_ == null) { + sourceContext_ = new global::Google.Protobuf.WellKnownTypes.SourceContext(); + } + SourceContext.MergeFrom(other.SourceContext); + } + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 10: { + Name = input.ReadString(); + break; + } + case 18: { + fields_.AddEntriesFrom(input, _repeated_fields_codec); + break; + } + case 26: { + oneofs_.AddEntriesFrom(input, _repeated_oneofs_codec); + break; + } + case 34: { + options_.AddEntriesFrom(input, _repeated_options_codec); + break; + } + case 42: { + if (sourceContext_ == null) { + sourceContext_ = new global::Google.Protobuf.WellKnownTypes.SourceContext(); + } + input.ReadMessage(sourceContext_); + break; + } + } + } + } + + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public sealed partial class Field : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Field()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.WellKnownTypes.Proto.Type.Descriptor.MessageTypes[1]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public Field() { + OnConstruction(); + } + + partial void OnConstruction(); + + public Field(Field other) : this() { + kind_ = other.kind_; + cardinality_ = other.cardinality_; + number_ = other.number_; + name_ = other.name_; + typeUrl_ = other.typeUrl_; + oneofIndex_ = other.oneofIndex_; + packed_ = other.packed_; + options_ = other.options_.Clone(); + } + + public Field Clone() { + return new Field(this); + } + + public const int KindFieldNumber = 1; + private global::Google.Protobuf.WellKnownTypes.Field.Types.Kind kind_ = global::Google.Protobuf.WellKnownTypes.Field.Types.Kind.TYPE_UNKNOWN; + public global::Google.Protobuf.WellKnownTypes.Field.Types.Kind Kind { + get { return kind_; } + set { + kind_ = value; + } + } + + public const int CardinalityFieldNumber = 2; + private global::Google.Protobuf.WellKnownTypes.Field.Types.Cardinality cardinality_ = global::Google.Protobuf.WellKnownTypes.Field.Types.Cardinality.CARDINALITY_UNKNOWN; + public global::Google.Protobuf.WellKnownTypes.Field.Types.Cardinality Cardinality { + get { return cardinality_; } + set { + cardinality_ = value; + } + } + + public const int NumberFieldNumber = 3; + private int number_; + public int Number { + get { return number_; } + set { + number_ = value; + } + } + + public const int NameFieldNumber = 4; + private string name_ = ""; + public string Name { + get { return name_; } + set { + name_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int TypeUrlFieldNumber = 6; + private string typeUrl_ = ""; + public string TypeUrl { + get { return typeUrl_; } + set { + typeUrl_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int OneofIndexFieldNumber = 7; + private int oneofIndex_; + public int OneofIndex { + get { return oneofIndex_; } + set { + oneofIndex_ = value; + } + } + + public const int PackedFieldNumber = 8; + private bool packed_; + public bool Packed { + get { return packed_; } + set { + packed_ = value; + } + } + + public const int OptionsFieldNumber = 9; + private static readonly pb::FieldCodec _repeated_options_codec + = pb::FieldCodec.ForMessage(74, global::Google.Protobuf.WellKnownTypes.Option.Parser); + private readonly pbc::RepeatedField options_ = new pbc::RepeatedField(); + public pbc::RepeatedField Options { + get { return options_; } + } + + public override bool Equals(object other) { + return Equals(other as Field); + } + + public bool Equals(Field other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Kind != other.Kind) return false; + if (Cardinality != other.Cardinality) return false; + if (Number != other.Number) return false; + if (Name != other.Name) return false; + if (TypeUrl != other.TypeUrl) return false; + if (OneofIndex != other.OneofIndex) return false; + if (Packed != other.Packed) return false; + if(!options_.Equals(other.options_)) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (Kind != global::Google.Protobuf.WellKnownTypes.Field.Types.Kind.TYPE_UNKNOWN) hash ^= Kind.GetHashCode(); + if (Cardinality != global::Google.Protobuf.WellKnownTypes.Field.Types.Cardinality.CARDINALITY_UNKNOWN) hash ^= Cardinality.GetHashCode(); + if (Number != 0) hash ^= Number.GetHashCode(); + if (Name.Length != 0) hash ^= Name.GetHashCode(); + if (TypeUrl.Length != 0) hash ^= TypeUrl.GetHashCode(); + if (OneofIndex != 0) hash ^= OneofIndex.GetHashCode(); + if (Packed != false) hash ^= Packed.GetHashCode(); + hash ^= options_.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (Kind != global::Google.Protobuf.WellKnownTypes.Field.Types.Kind.TYPE_UNKNOWN) { + output.WriteRawTag(8); + output.WriteEnum((int) Kind); + } + if (Cardinality != global::Google.Protobuf.WellKnownTypes.Field.Types.Cardinality.CARDINALITY_UNKNOWN) { + output.WriteRawTag(16); + output.WriteEnum((int) Cardinality); + } + if (Number != 0) { + output.WriteRawTag(24); + output.WriteInt32(Number); + } + if (Name.Length != 0) { + output.WriteRawTag(34); + output.WriteString(Name); + } + if (TypeUrl.Length != 0) { + output.WriteRawTag(50); + output.WriteString(TypeUrl); + } + if (OneofIndex != 0) { + output.WriteRawTag(56); + output.WriteInt32(OneofIndex); + } + if (Packed != false) { + output.WriteRawTag(64); + output.WriteBool(Packed); + } + options_.WriteTo(output, _repeated_options_codec); + } + + public int CalculateSize() { + int size = 0; + if (Kind != global::Google.Protobuf.WellKnownTypes.Field.Types.Kind.TYPE_UNKNOWN) { + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Kind); + } + if (Cardinality != global::Google.Protobuf.WellKnownTypes.Field.Types.Cardinality.CARDINALITY_UNKNOWN) { + size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Cardinality); + } + if (Number != 0) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Number); + } + if (Name.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); + } + if (TypeUrl.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(TypeUrl); + } + if (OneofIndex != 0) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(OneofIndex); + } + if (Packed != false) { + size += 1 + 1; + } + size += options_.CalculateSize(_repeated_options_codec); + return size; + } + + public void MergeFrom(Field other) { + if (other == null) { + return; + } + if (other.Kind != global::Google.Protobuf.WellKnownTypes.Field.Types.Kind.TYPE_UNKNOWN) { + Kind = other.Kind; + } + if (other.Cardinality != global::Google.Protobuf.WellKnownTypes.Field.Types.Cardinality.CARDINALITY_UNKNOWN) { + Cardinality = other.Cardinality; + } + if (other.Number != 0) { + Number = other.Number; + } + if (other.Name.Length != 0) { + Name = other.Name; + } + if (other.TypeUrl.Length != 0) { + TypeUrl = other.TypeUrl; + } + if (other.OneofIndex != 0) { + OneofIndex = other.OneofIndex; + } + if (other.Packed != false) { + Packed = other.Packed; + } + options_.Add(other.options_); + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 8: { + kind_ = (global::Google.Protobuf.WellKnownTypes.Field.Types.Kind) input.ReadEnum(); + break; + } + case 16: { + cardinality_ = (global::Google.Protobuf.WellKnownTypes.Field.Types.Cardinality) input.ReadEnum(); + break; + } + case 24: { + Number = input.ReadInt32(); + break; + } + case 34: { + Name = input.ReadString(); + break; + } + case 50: { + TypeUrl = input.ReadString(); + break; + } + case 56: { + OneofIndex = input.ReadInt32(); + break; + } + case 64: { + Packed = input.ReadBool(); + break; + } + case 74: { + options_.AddEntriesFrom(input, _repeated_options_codec); + break; + } + } + } + } + + #region Nested types + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public static partial class Types { + public enum Kind { + TYPE_UNKNOWN = 0, + TYPE_DOUBLE = 1, + TYPE_FLOAT = 2, + TYPE_INT64 = 3, + TYPE_UINT64 = 4, + TYPE_INT32 = 5, + TYPE_FIXED64 = 6, + TYPE_FIXED32 = 7, + TYPE_BOOL = 8, + TYPE_STRING = 9, + TYPE_MESSAGE = 11, + TYPE_BYTES = 12, + TYPE_UINT32 = 13, + TYPE_ENUM = 14, + TYPE_SFIXED32 = 15, + TYPE_SFIXED64 = 16, + TYPE_SINT32 = 17, + TYPE_SINT64 = 18, + } + + public enum Cardinality { + CARDINALITY_UNKNOWN = 0, + CARDINALITY_OPTIONAL = 1, + CARDINALITY_REQUIRED = 2, + CARDINALITY_REPEATED = 3, + } + + } + #endregion + + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public sealed partial class Enum : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new Enum()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.WellKnownTypes.Proto.Type.Descriptor.MessageTypes[2]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public Enum() { + OnConstruction(); + } + + partial void OnConstruction(); + + public Enum(Enum other) : this() { + name_ = other.name_; + enumvalue_ = other.enumvalue_.Clone(); + options_ = other.options_.Clone(); + SourceContext = other.sourceContext_ != null ? other.SourceContext.Clone() : null; + } + + public Enum Clone() { + return new Enum(this); + } + + public const int NameFieldNumber = 1; + private string name_ = ""; + public string Name { + get { return name_; } + set { + name_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int EnumvalueFieldNumber = 2; + private static readonly pb::FieldCodec _repeated_enumvalue_codec + = pb::FieldCodec.ForMessage(18, global::Google.Protobuf.WellKnownTypes.EnumValue.Parser); + private readonly pbc::RepeatedField enumvalue_ = new pbc::RepeatedField(); + public pbc::RepeatedField Enumvalue { + get { return enumvalue_; } + } + + public const int OptionsFieldNumber = 3; + private static readonly pb::FieldCodec _repeated_options_codec + = pb::FieldCodec.ForMessage(26, global::Google.Protobuf.WellKnownTypes.Option.Parser); + private readonly pbc::RepeatedField options_ = new pbc::RepeatedField(); + public pbc::RepeatedField Options { + get { return options_; } + } + + public const int SourceContextFieldNumber = 4; + private global::Google.Protobuf.WellKnownTypes.SourceContext sourceContext_; + public global::Google.Protobuf.WellKnownTypes.SourceContext SourceContext { + get { return sourceContext_; } + set { + sourceContext_ = value; + } + } + + public override bool Equals(object other) { + return Equals(other as Enum); + } + + public bool Equals(Enum other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Name != other.Name) return false; + if(!enumvalue_.Equals(other.enumvalue_)) return false; + if(!options_.Equals(other.options_)) return false; + if (!object.Equals(SourceContext, other.SourceContext)) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (Name.Length != 0) hash ^= Name.GetHashCode(); + hash ^= enumvalue_.GetHashCode(); + hash ^= options_.GetHashCode(); + if (sourceContext_ != null) hash ^= SourceContext.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (Name.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Name); + } + enumvalue_.WriteTo(output, _repeated_enumvalue_codec); + options_.WriteTo(output, _repeated_options_codec); + if (sourceContext_ != null) { + output.WriteRawTag(34); + output.WriteMessage(SourceContext); + } + } + + public int CalculateSize() { + int size = 0; + if (Name.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); + } + size += enumvalue_.CalculateSize(_repeated_enumvalue_codec); + size += options_.CalculateSize(_repeated_options_codec); + if (sourceContext_ != null) { + size += 1 + pb::CodedOutputStream.ComputeMessageSize(SourceContext); + } + return size; + } + + public void MergeFrom(Enum other) { + if (other == null) { + return; + } + if (other.Name.Length != 0) { + Name = other.Name; + } + enumvalue_.Add(other.enumvalue_); + options_.Add(other.options_); + if (other.sourceContext_ != null) { + if (sourceContext_ == null) { + sourceContext_ = new global::Google.Protobuf.WellKnownTypes.SourceContext(); + } + SourceContext.MergeFrom(other.SourceContext); + } + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 10: { + Name = input.ReadString(); + break; + } + case 18: { + enumvalue_.AddEntriesFrom(input, _repeated_enumvalue_codec); + break; + } + case 26: { + options_.AddEntriesFrom(input, _repeated_options_codec); + break; + } + case 34: { + if (sourceContext_ == null) { + sourceContext_ = new global::Google.Protobuf.WellKnownTypes.SourceContext(); + } + input.ReadMessage(sourceContext_); + break; + } + } + } + } + + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public sealed partial class EnumValue : pb::IMessage { + private static readonly pb::MessageParser _parser = new pb::MessageParser(() => new EnumValue()); + public static pb::MessageParser Parser { get { return _parser; } } + + public static pbr::MessageDescriptor Descriptor { + get { return global::Google.Protobuf.WellKnownTypes.Proto.Type.Descriptor.MessageTypes[3]; } + } + + pbr::MessageDescriptor pb::IMessage.Descriptor { + get { return Descriptor; } + } + + public EnumValue() { + OnConstruction(); + } + + partial void OnConstruction(); + + public EnumValue(EnumValue other) : this() { + name_ = other.name_; + number_ = other.number_; + options_ = other.options_.Clone(); + } + + public EnumValue Clone() { + return new EnumValue(this); + } + + public const int NameFieldNumber = 1; + private string name_ = ""; + public string Name { + get { return name_; } + set { + name_ = pb::Preconditions.CheckNotNull(value, "value"); + } + } + + public const int NumberFieldNumber = 2; + private int number_; + public int Number { + get { return number_; } + set { + number_ = value; + } + } + + public const int OptionsFieldNumber = 3; + private static readonly pb::FieldCodec _repeated_options_codec + = pb::FieldCodec.ForMessage(26, global::Google.Protobuf.WellKnownTypes.Option.Parser); + private readonly pbc::RepeatedField options_ = new pbc::RepeatedField(); + public pbc::RepeatedField Options { + get { return options_; } + } + + public override bool Equals(object other) { + return Equals(other as EnumValue); + } + + public bool Equals(EnumValue other) { + if (ReferenceEquals(other, null)) { + return false; + } + if (ReferenceEquals(other, this)) { + return true; + } + if (Name != other.Name) return false; + if (Number != other.Number) return false; + if(!options_.Equals(other.options_)) return false; + return true; + } + + public override int GetHashCode() { + int hash = 1; + if (Name.Length != 0) hash ^= Name.GetHashCode(); + if (Number != 0) hash ^= Number.GetHashCode(); + hash ^= options_.GetHashCode(); + return hash; + } + + public override string ToString() { + return pb::JsonFormatter.Default.Format(this); + } + + public void WriteTo(pb::CodedOutputStream output) { + if (Name.Length != 0) { + output.WriteRawTag(10); + output.WriteString(Name); + } + if (Number != 0) { + output.WriteRawTag(16); + output.WriteInt32(Number); + } + options_.WriteTo(output, _repeated_options_codec); + } + + public int CalculateSize() { + int size = 0; + if (Name.Length != 0) { + size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); + } + if (Number != 0) { + size += 1 + pb::CodedOutputStream.ComputeInt32Size(Number); + } + size += options_.CalculateSize(_repeated_options_codec); + return size; + } + + public void MergeFrom(EnumValue other) { + if (other == null) { + return; + } + if (other.Name.Length != 0) { + Name = other.Name; + } + if (other.Number != 0) { + Number = other.Number; + } + options_.Add(other.options_); + } + + public void MergeFrom(pb::CodedInputStream input) { + uint tag; + while ((tag = input.ReadTag()) != 0) { + switch(tag) { + default: + input.SkipLastField(); + break; + case 10: { + Name = input.ReadString(); + break; + } + case 16: { + Number = input.ReadInt32(); + break; + } + case 26: { + options_.AddEntriesFrom(input, _repeated_options_codec); + break; + } + } + } + } + + } + + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + public sealed partial class Option : pb::IMessage