From e38294a62d7f37c0661273a9a26fda16d557423f Mon Sep 17 00:00:00 2001 From: Jon Skeet Date: Tue, 9 Jun 2015 19:30:44 +0100 Subject: First pass at the mutable API. Quite a bit more to do - in particular, it's pretty slow right now. --- csharp/protos/extest/unittest_issues.proto | 86 +- .../ProtocolBuffers.Test/AbstractMessageTest.cs | 548 - csharp/src/ProtocolBuffers.Test/ByteStringTest.cs | 2 +- .../ProtocolBuffers.Test/CodedInputStreamTest.cs | 64 +- .../ProtocolBuffers.Test/CodedOutputStreamTest.cs | 23 +- .../Collections/PopsicleListTest.cs | 125 - .../Compatibility/BinaryCompatibilityTests.cs | 18 - .../Compatibility/CompatibilityTests.cs | 227 - .../Compatibility/DictionaryCompatibilityTests.cs | 35 - .../Compatibility/JsonCompatibilityTests.cs | 43 - .../Compatibility/TestResources.cs | 38 - .../Compatibility/TextCompatibilityTests.cs | 35 - .../Compatibility/XmlCompatibilityTests.cs | 45 - .../Compatibility/google_message1.dat | Bin 228 -> 0 bytes .../Compatibility/google_message2.dat | Bin 84570 -> 0 bytes .../ProtocolBuffers.Test/DeprecatedMemberTest.cs | 82 +- csharp/src/ProtocolBuffers.Test/DescriptorsTest.cs | 152 +- .../src/ProtocolBuffers.Test/DynamicMessageTest.cs | 276 - .../ProtocolBuffers.Test/ExtendableMessageTest.cs | 200 - .../src/ProtocolBuffers.Test/FieldPresenceTest.cs | 198 - .../ProtocolBuffers.Test/GeneratedBuilderTest.cs | 102 - .../ProtocolBuffers.Test/GeneratedMessageTest.cs | 911 +- csharp/src/ProtocolBuffers.Test/IssuesTest.cs | 10 +- .../MessageStreamIteratorTest.cs | 90 - .../MessageStreamWriterTest.cs | 78 - csharp/src/ProtocolBuffers.Test/MessageTest.cs | 344 - csharp/src/ProtocolBuffers.Test/MessageUtilTest.cs | 82 - csharp/src/ProtocolBuffers.Test/NameHelpersTest.cs | 81 - .../ProtocolBuffers.Test.csproj | 62 +- .../src/ProtocolBuffers.Test/ReflectionTester.cs | 1033 - .../src/ProtocolBuffers.Test/RepeatedFieldTest.cs | 50 + .../ProtocolBuffers.Test/ReusableBuilderTest.cs | 166 - csharp/src/ProtocolBuffers.Test/TestCornerCases.cs | 22 +- .../ProtocolBuffers.Test/TestMimeMessageFormats.cs | 277 - .../ProtocolBuffers.Test/TestProtos/GoogleSize.cs | 4547 --- .../ProtocolBuffers.Test/TestProtos/GoogleSpeed.cs | 6612 ---- .../ProtocolBuffers.Test/TestProtos/Unittest.cs | 33878 ----------------- .../TestProtos/UnittestCustomOptions.cs | 7543 ---- .../TestProtos/UnittestDropUnknownFields.cs | 732 - .../TestProtos/UnittestEnormousDescriptor.cs | 36189 ------------------- .../TestProtos/UnittestExtrasXmltest.cs | 2277 -- .../TestProtos/UnittestImport.cs | 347 - .../TestProtos/UnittestImportProto3.cs | 165 + .../TestProtos/UnittestImportPublic.cs | 333 - .../TestProtos/UnittestImportPublicProto3.cs | 150 + .../TestProtos/UnittestIssues.cs | 2571 +- .../TestProtos/UnittestMset.cs | 1824 - .../TestProtos/UnittestNoFieldPresence.cs | 3876 -- .../TestProtos/UnittestOptimizeFor.cs | 738 - .../TestProtos/UnittestProto3.cs | 6060 ++++ .../TestProtos/UnknownEnumTest.cs | 809 - .../TestReaderForUrlEncoded.cs | 83 - csharp/src/ProtocolBuffers.Test/TestResources.cs | 301 - csharp/src/ProtocolBuffers.Test/TestUtil.cs | 1862 - .../ProtocolBuffers.Test/TestWriterFormatJson.cs | 498 - .../ProtocolBuffers.Test/TestWriterFormatXml.cs | 468 - csharp/src/ProtocolBuffers.Test/TextFormatTest.cs | 560 - .../ProtocolBuffers.Test/UnknownFieldSetTest.cs | 431 - csharp/src/ProtocolBuffers.Test/WireFormatTest.cs | 255 +- csharp/src/ProtocolBuffers/AbstractBuilder.cs | 274 - csharp/src/ProtocolBuffers/AbstractBuilderLite.cs | 264 - csharp/src/ProtocolBuffers/AbstractMessage.cs | 293 - csharp/src/ProtocolBuffers/AbstractMessageLite.cs | 140 - csharp/src/ProtocolBuffers/ByteArray.cs | 2 +- csharp/src/ProtocolBuffers/ByteString.cs | 20 +- csharp/src/ProtocolBuffers/CodedInputStream.cs | 163 +- .../CodedOutputStream.ComputeSize.cs | 71 +- csharp/src/ProtocolBuffers/CodedOutputStream.cs | 338 +- .../ProtocolBuffers/Collections/Dictionaries.cs | 2 +- .../src/ProtocolBuffers/Collections/Enumerables.cs | 2 +- .../ProtocolBuffers/Collections/IPopsicleList.cs | 58 - csharp/src/ProtocolBuffers/Collections/Lists.cs | 2 +- .../ProtocolBuffers/Collections/PopsicleList.cs | 208 - .../Collections/ReadOnlyDictionary.cs | 2 +- .../ProtocolBuffers/Collections/RepeatedField.cs | 168 + .../Collections/RepeatedFieldExtensions.cs | 47 + csharp/src/ProtocolBuffers/Delegates.cs | 54 - .../DescriptorProtos/DescriptorProtoFile.cs | 12724 ++----- .../DescriptorProtos/IDescriptorProto.cs | 2 +- .../DescriptorProtos/PartialClasses.cs | 2 +- .../ProtocolBuffers/Descriptors/DescriptorBase.cs | 5 +- .../ProtocolBuffers/Descriptors/DescriptorPool.cs | 4 +- .../ProtocolBuffers/Descriptors/DescriptorUtil.cs | 4 +- .../Descriptors/DescriptorValidationException.cs | 13 +- .../ProtocolBuffers/Descriptors/EnumDescriptor.cs | 31 +- .../Descriptors/EnumValueDescriptor.cs | 7 +- .../ProtocolBuffers/Descriptors/FieldDescriptor.cs | 223 +- .../Descriptors/FieldMappingAttribute.cs | 4 +- .../src/ProtocolBuffers/Descriptors/FieldType.cs | 2 +- .../ProtocolBuffers/Descriptors/FileDescriptor.cs | 55 +- .../src/ProtocolBuffers/Descriptors/IDescriptor.cs | 4 +- .../Descriptors/IndexedDescriptorBase.cs | 4 +- .../src/ProtocolBuffers/Descriptors/MappedType.cs | 2 +- .../Descriptors/MessageDescriptor.cs | 30 +- .../Descriptors/MethodDescriptor.cs | 4 +- .../ProtocolBuffers/Descriptors/OneofDescriptor.cs | 4 +- .../Descriptors/PackageDescriptor.cs | 2 +- .../Descriptors/ServiceDescriptor.cs | 8 +- csharp/src/ProtocolBuffers/DynamicMessage.cs | 624 - csharp/src/ProtocolBuffers/EnumHelper.cs | 85 + csharp/src/ProtocolBuffers/EnumLite.cs | 234 - csharp/src/ProtocolBuffers/ExtendableBuilder.cs | 212 - .../src/ProtocolBuffers/ExtendableBuilderLite.cs | 345 - csharp/src/ProtocolBuffers/ExtendableMessage.cs | 274 - .../src/ProtocolBuffers/ExtendableMessageLite.cs | 221 - csharp/src/ProtocolBuffers/ExtensionInfo.cs | 88 - csharp/src/ProtocolBuffers/ExtensionRegistry.cs | 215 - .../src/ProtocolBuffers/ExtensionRegistryLite.cs | 232 - csharp/src/ProtocolBuffers/Extensions.cs | 70 + .../FieldAccess/FieldAccessorBase.cs | 38 + .../FieldAccess/FieldAccessorTable.cs | 104 +- .../ProtocolBuffers/FieldAccess/IFieldAccessor.cs | 59 +- .../ProtocolBuffers/FieldAccess/OneofAccessor.cs | 13 +- .../ProtocolBuffers/FieldAccess/ReflectionUtil.cs | 57 +- .../FieldAccess/RepeatedEnumAccessor.cs | 83 - .../FieldAccess/RepeatedFieldAccessor.cs | 37 + .../FieldAccess/RepeatedMessageAccessor.cs | 97 - .../FieldAccess/RepeatedPrimitiveAccessor.cs | 158 - .../FieldAccess/SingleEnumAccessor.cs | 75 - .../FieldAccess/SingleFieldAccessor.cs | 89 + .../FieldAccess/SingleMessageAccessor.cs | 91 - .../FieldAccess/SinglePrimitiveAccessor.cs | 162 - csharp/src/ProtocolBuffers/FieldSet.cs | 632 - csharp/src/ProtocolBuffers/FrameworkPortability.cs | 2 +- csharp/src/ProtocolBuffers/GeneratedBuilder.cs | 230 - csharp/src/ProtocolBuffers/GeneratedBuilderLite.cs | 100 - .../src/ProtocolBuffers/GeneratedExtensionBase.cs | 185 - .../src/ProtocolBuffers/GeneratedExtensionLite.cs | 354 - csharp/src/ProtocolBuffers/GeneratedMessage.cs | 191 - csharp/src/ProtocolBuffers/GeneratedMessageLite.cs | 182 - .../ProtocolBuffers/GeneratedRepeatExtension.cs | 88 - .../ProtocolBuffers/GeneratedSingleExtension.cs | 65 - csharp/src/ProtocolBuffers/IBuilder.cs | 323 - csharp/src/ProtocolBuffers/IBuilderLite.cs | 213 - csharp/src/ProtocolBuffers/ICodedInputStream.cs | 50 +- csharp/src/ProtocolBuffers/ICodedOutputStream.cs | 103 +- csharp/src/ProtocolBuffers/IMessage.cs | 216 +- csharp/src/ProtocolBuffers/IMessageLite.cs | 188 - .../InvalidProtocolBufferException.cs | 2 +- csharp/src/ProtocolBuffers/LimitedInputStream.cs | 78 + csharp/src/ProtocolBuffers/MessageParser.cs | 57 + .../src/ProtocolBuffers/MessageStreamIterator.cs | 170 - csharp/src/ProtocolBuffers/MessageStreamWriter.cs | 70 - csharp/src/ProtocolBuffers/MessageUtil.cs | 109 - csharp/src/ProtocolBuffers/NameHelpers.cs | 140 - csharp/src/ProtocolBuffers/ProtocolBuffers.csproj | 61 +- csharp/src/ProtocolBuffers/SortedList.cs | 167 - csharp/src/ProtocolBuffers/TextFormat.cs | 893 - csharp/src/ProtocolBuffers/TextGenerator.cs | 2 +- csharp/src/ProtocolBuffers/TextTokenizer.cs | 501 - csharp/src/ProtocolBuffers/ThrowHelper.cs | 2 +- .../UninitializedMessageException.cs | 208 - csharp/src/ProtocolBuffers/UnknownField.cs | 415 - csharp/src/ProtocolBuffers/UnknownFieldSet.cs | 1061 - csharp/src/ProtocolBuffers/WireFormat.cs | 4 +- .../protobuf/compiler/csharp/csharp_enum_field.cc | 8 +- .../protobuf/compiler/csharp/csharp_field_base.cc | 19 +- .../protobuf/compiler/csharp/csharp_message.cc | 99 +- .../protobuf/compiler/csharp/csharp_message.h | 1 + .../compiler/csharp/csharp_message_field.cc | 30 +- .../compiler/csharp/csharp_primitive_field.cc | 16 +- .../compiler/csharp/csharp_repeated_enum_field.cc | 25 +- .../csharp/csharp_repeated_message_field.cc | 27 +- .../csharp/csharp_repeated_primitive_field.cc | 10 +- src/google/protobuf/descriptor.proto | 2 +- src/google/protobuf/unittest_import_proto3.proto | 68 + .../protobuf/unittest_import_public_proto3.proto | 42 + src/google/protobuf/unittest_proto3.proto | 388 + 168 files changed, 11868 insertions(+), 133448 deletions(-) delete mode 100644 csharp/src/ProtocolBuffers.Test/AbstractMessageTest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/Collections/PopsicleListTest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/Compatibility/BinaryCompatibilityTests.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/Compatibility/CompatibilityTests.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/Compatibility/DictionaryCompatibilityTests.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/Compatibility/JsonCompatibilityTests.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/Compatibility/TestResources.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/Compatibility/TextCompatibilityTests.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/Compatibility/XmlCompatibilityTests.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/Compatibility/google_message1.dat delete mode 100644 csharp/src/ProtocolBuffers.Test/Compatibility/google_message2.dat delete mode 100644 csharp/src/ProtocolBuffers.Test/DynamicMessageTest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/ExtendableMessageTest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/FieldPresenceTest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/GeneratedBuilderTest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/MessageStreamIteratorTest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/MessageStreamWriterTest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/MessageTest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/MessageUtilTest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/NameHelpersTest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/ReflectionTester.cs create mode 100644 csharp/src/ProtocolBuffers.Test/RepeatedFieldTest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/ReusableBuilderTest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestMimeMessageFormats.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestProtos/GoogleSize.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestProtos/GoogleSpeed.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestProtos/Unittest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestProtos/UnittestCustomOptions.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestProtos/UnittestDropUnknownFields.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestProtos/UnittestEnormousDescriptor.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestProtos/UnittestExtrasXmltest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImport.cs create mode 100644 csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImportProto3.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImportPublic.cs create mode 100644 csharp/src/ProtocolBuffers.Test/TestProtos/UnittestImportPublicProto3.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestProtos/UnittestMset.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestProtos/UnittestNoFieldPresence.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestProtos/UnittestOptimizeFor.cs create mode 100644 csharp/src/ProtocolBuffers.Test/TestProtos/UnittestProto3.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestProtos/UnknownEnumTest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestReaderForUrlEncoded.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestResources.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestUtil.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestWriterFormatJson.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TestWriterFormatXml.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/TextFormatTest.cs delete mode 100644 csharp/src/ProtocolBuffers.Test/UnknownFieldSetTest.cs delete mode 100644 csharp/src/ProtocolBuffers/AbstractBuilder.cs delete mode 100644 csharp/src/ProtocolBuffers/AbstractBuilderLite.cs delete mode 100644 csharp/src/ProtocolBuffers/AbstractMessage.cs delete mode 100644 csharp/src/ProtocolBuffers/AbstractMessageLite.cs delete mode 100644 csharp/src/ProtocolBuffers/Collections/IPopsicleList.cs delete mode 100644 csharp/src/ProtocolBuffers/Collections/PopsicleList.cs create mode 100644 csharp/src/ProtocolBuffers/Collections/RepeatedField.cs create mode 100644 csharp/src/ProtocolBuffers/Collections/RepeatedFieldExtensions.cs delete mode 100644 csharp/src/ProtocolBuffers/Delegates.cs delete mode 100644 csharp/src/ProtocolBuffers/DynamicMessage.cs create mode 100644 csharp/src/ProtocolBuffers/EnumHelper.cs delete mode 100644 csharp/src/ProtocolBuffers/EnumLite.cs delete mode 100644 csharp/src/ProtocolBuffers/ExtendableBuilder.cs delete mode 100644 csharp/src/ProtocolBuffers/ExtendableBuilderLite.cs delete mode 100644 csharp/src/ProtocolBuffers/ExtendableMessage.cs delete mode 100644 csharp/src/ProtocolBuffers/ExtendableMessageLite.cs delete mode 100644 csharp/src/ProtocolBuffers/ExtensionInfo.cs delete mode 100644 csharp/src/ProtocolBuffers/ExtensionRegistry.cs delete mode 100644 csharp/src/ProtocolBuffers/ExtensionRegistryLite.cs create mode 100644 csharp/src/ProtocolBuffers/Extensions.cs create mode 100644 csharp/src/ProtocolBuffers/FieldAccess/FieldAccessorBase.cs delete mode 100644 csharp/src/ProtocolBuffers/FieldAccess/RepeatedEnumAccessor.cs create mode 100644 csharp/src/ProtocolBuffers/FieldAccess/RepeatedFieldAccessor.cs delete mode 100644 csharp/src/ProtocolBuffers/FieldAccess/RepeatedMessageAccessor.cs delete mode 100644 csharp/src/ProtocolBuffers/FieldAccess/RepeatedPrimitiveAccessor.cs delete mode 100644 csharp/src/ProtocolBuffers/FieldAccess/SingleEnumAccessor.cs create mode 100644 csharp/src/ProtocolBuffers/FieldAccess/SingleFieldAccessor.cs delete mode 100644 csharp/src/ProtocolBuffers/FieldAccess/SingleMessageAccessor.cs delete mode 100644 csharp/src/ProtocolBuffers/FieldAccess/SinglePrimitiveAccessor.cs delete mode 100644 csharp/src/ProtocolBuffers/FieldSet.cs delete mode 100644 csharp/src/ProtocolBuffers/GeneratedBuilder.cs delete mode 100644 csharp/src/ProtocolBuffers/GeneratedBuilderLite.cs delete mode 100644 csharp/src/ProtocolBuffers/GeneratedExtensionBase.cs delete mode 100644 csharp/src/ProtocolBuffers/GeneratedExtensionLite.cs delete mode 100644 csharp/src/ProtocolBuffers/GeneratedMessage.cs delete mode 100644 csharp/src/ProtocolBuffers/GeneratedMessageLite.cs delete mode 100644 csharp/src/ProtocolBuffers/GeneratedRepeatExtension.cs delete mode 100644 csharp/src/ProtocolBuffers/GeneratedSingleExtension.cs delete mode 100644 csharp/src/ProtocolBuffers/IBuilder.cs delete mode 100644 csharp/src/ProtocolBuffers/IBuilderLite.cs delete mode 100644 csharp/src/ProtocolBuffers/IMessageLite.cs create mode 100644 csharp/src/ProtocolBuffers/LimitedInputStream.cs create mode 100644 csharp/src/ProtocolBuffers/MessageParser.cs delete mode 100644 csharp/src/ProtocolBuffers/MessageStreamIterator.cs delete mode 100644 csharp/src/ProtocolBuffers/MessageStreamWriter.cs delete mode 100644 csharp/src/ProtocolBuffers/MessageUtil.cs delete mode 100644 csharp/src/ProtocolBuffers/NameHelpers.cs delete mode 100644 csharp/src/ProtocolBuffers/SortedList.cs delete mode 100644 csharp/src/ProtocolBuffers/TextFormat.cs delete mode 100644 csharp/src/ProtocolBuffers/TextTokenizer.cs delete mode 100644 csharp/src/ProtocolBuffers/UninitializedMessageException.cs delete mode 100644 csharp/src/ProtocolBuffers/UnknownField.cs delete mode 100644 csharp/src/ProtocolBuffers/UnknownFieldSet.cs create mode 100644 src/google/protobuf/unittest_import_proto3.proto create mode 100644 src/google/protobuf/unittest_import_public_proto3.proto create mode 100644 src/google/protobuf/unittest_proto3.proto diff --git a/csharp/protos/extest/unittest_issues.proto b/csharp/protos/extest/unittest_issues.proto index 97249dff..c123acf1 100644 --- a/csharp/protos/extest/unittest_issues.proto +++ b/csharp/protos/extest/unittest_issues.proto @@ -1,4 +1,4 @@ -syntax = "proto2"; +syntax = "proto3"; // These proto descriptors have at one time been reported as an issue or defect. // They are kept here to replicate the issue, and continue to verify the fix. @@ -9,65 +9,6 @@ option csharp_namespace = "UnitTest.Issues.TestProtos"; package unittest_issues; option optimize_for = SPEED; -// The following is a representative set of features -/* -enum EnumOptions { - ONE = 0; - TWO = 1; - THREE = 2; -} - -message TestBasicChild -{ - repeated EnumOptions options = 3; - optional bytes binary = 4; -} - -message TestBasicNoFields { -} - -message TestBasicRescursive { - optional TestBasicRescursive child = 1; -} - -message TestBasicMessage { - - optional int64 number = 6; - repeated int32 numbers = 2; - optional string text = 3; - repeated string textlines = 700; - optional bool valid = 5; - - optional TestBasicChild child = 1; - repeated group Children = 401 - { - repeated EnumOptions options = 3; - optional bytes binary = 4; - } - - extensions 100 to 199; -} - -message TestBasicExtension { - required int32 number = 1; -} - -extend TestBasicMessage { - optional EnumOptions extension_enum = 101; - optional string extension_text = 102; - repeated int32 extension_number = 103 [packed = true]; - optional TestBasicExtension extension_message = 199; -} - -// Issue for non-qualified type reference in new services generation -option (google.protobuf.csharp_file_options).service_generator_type = IRPCDISPATCH; - -service TestGenericService { - rpc Foo(TestBasicNoFields) returns (TestBasicMessage); - rpc Bar(TestBasicNoFields) returns (TestBasicMessage); -} -*/ - // Old issue 13: http://code.google.com/p/protobuf-csharp-port/issues/detail?id=13 // New issue 309: https://github.com/google/protobuf/issues/309 @@ -90,27 +31,17 @@ service TestGenericService { // optional int32 _01 = 1; // } -// Issue 28: Circular message dependencies result in null defaults for DefaultInstance - -message MyMessageAReferenceB { - required MyMessageBReferenceA value = 1; -} - -message MyMessageBReferenceA { - required MyMessageAReferenceB value = 1; -} - // issue 19 - negative enum values enum NegativeEnum { + NEGATIVE_ENUM_ZERO = 0; FiveBelow = -5; MinusOne = -1; - Zero = 0; } message NegativeEnumMessage { - optional NegativeEnum value = 1; - repeated NegativeEnum values = 2; + NegativeEnum value = 1; + repeated NegativeEnum values = 2 [packed = false]; repeated NegativeEnum packed_values = 3 [packed=true]; } @@ -121,21 +52,22 @@ message DeprecatedChild { } enum DeprecatedEnum { + DEPRECATED_ZERO = 0; one = 1; } message DeprecatedFieldsMessage { - optional int32 PrimitiveValue = 1 [deprecated = true]; + int32 PrimitiveValue = 1 [deprecated = true]; repeated int32 PrimitiveArray = 2 [deprecated = true]; - optional DeprecatedChild MessageValue = 3 [deprecated = true]; + DeprecatedChild MessageValue = 3 [deprecated = true]; repeated DeprecatedChild MessageArray = 4 [deprecated = true]; - optional DeprecatedEnum EnumValue = 5 [deprecated = true]; + DeprecatedEnum EnumValue = 5 [deprecated = true]; repeated DeprecatedEnum EnumArray = 6 [deprecated = true]; } // Issue 45: http://code.google.com/p/protobuf-csharp-port/issues/detail?id=45 message ItemField { - optional int32 item = 1; + int32 item = 1; } diff --git a/csharp/src/ProtocolBuffers.Test/AbstractMessageTest.cs b/csharp/src/ProtocolBuffers.Test/AbstractMessageTest.cs deleted file mode 100644 index 8118808b..00000000 --- a/csharp/src/ProtocolBuffers.Test/AbstractMessageTest.cs +++ /dev/null @@ -1,548 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using System.IO; -using Google.ProtocolBuffers.Descriptors; -using Google.ProtocolBuffers.TestProtos; -using NUnit.Framework; - -namespace Google.ProtocolBuffers -{ - public class AbstractMessageTest - { - [Test] - public void Clear() - { - AbstractMessageWrapper message = - new AbstractMessageWrapper.Builder(TestAllTypes.CreateBuilder(TestUtil.GetAllSet())).Clear().Build(); - TestUtil.AssertClear((TestAllTypes) message.WrappedMessage); - } - - [Test] - public void Copy() - { - AbstractMessageWrapper message = - new AbstractMessageWrapper.Builder(TestAllTypes.CreateBuilder()).MergeFrom(TestUtil.GetAllSet()).Build(); - TestUtil.AssertAllFieldsSet((TestAllTypes) message.WrappedMessage); - } - - [Test] - public void CreateAndBuild() - { - TestAllTypes.CreateBuilder() - .Build(); - } - - [Test] - public void SerializedSize() - { - TestAllTypes message = TestUtil.GetAllSet(); - IMessage abstractMessage = new AbstractMessageWrapper(TestUtil.GetAllSet()); - - Assert.AreEqual(message.SerializedSize, abstractMessage.SerializedSize); - } - - [Test] - public void Serialization() - { - IMessage abstractMessage = new AbstractMessageWrapper(TestUtil.GetAllSet()); - TestUtil.AssertAllFieldsSet(TestAllTypes.ParseFrom(abstractMessage.ToByteString())); - Assert.AreEqual(TestUtil.GetAllSet().ToByteString(), abstractMessage.ToByteString()); - } - - [Test] - public void Parsing() - { - IBuilder builder = new AbstractMessageWrapper.Builder(TestAllTypes.CreateBuilder()); - AbstractMessageWrapper message = - (AbstractMessageWrapper) builder.WeakMergeFrom(TestUtil.GetAllSet().ToByteString()).WeakBuild(); - TestUtil.AssertAllFieldsSet((TestAllTypes) message.WrappedMessage); - } - - [Test] - public void PackedSerialization() - { - IMessage abstractMessage = new AbstractMessageWrapper(TestUtil.GetPackedSet()); - TestUtil.AssertPackedFieldsSet(TestPackedTypes.ParseFrom(abstractMessage.ToByteString())); - Assert.AreEqual(TestUtil.GetPackedSet().ToByteString(), abstractMessage.ToByteString()); - } - - [Test] - public void PackedParsing() - { - AbstractMessageWrapper.Builder builder = new AbstractMessageWrapper.Builder(TestPackedTypes.CreateBuilder()); - AbstractMessageWrapper message = builder.MergeFrom(TestUtil.GetPackedSet().ToByteString()).Build(); - TestUtil.AssertPackedFieldsSet((TestPackedTypes)message.WrappedMessage); - } - - [Test] - public void UnpackedParsingOfPackedInput() - { - byte[] bytes = TestUtil.GetPackedSet().ToByteArray(); - TestUnpackedTypes message = TestUnpackedTypes.ParseFrom(bytes); - TestUtil.AssertUnpackedFieldsSet(message); - } - - [Test] - public void PackedParsingOfUnpackedInput() - { - byte[] bytes = TestUnpackedTypes.ParseFrom(TestUtil.GetPackedSet().ToByteArray()).ToByteArray(); - TestPackedTypes message = TestPackedTypes.ParseFrom(bytes); - TestUtil.AssertPackedFieldsSet(message); - } - - [Test] - public void UnpackedParsingOfPackedInputExtensions() - { - byte[] bytes = TestUtil.GetPackedSet().ToByteArray(); - ExtensionRegistry registry = ExtensionRegistry.CreateInstance(); - Unittest.RegisterAllExtensions(registry); - UnittestImport.RegisterAllExtensions(registry); - TestUnpackedExtensions message = TestUnpackedExtensions.ParseFrom(bytes, registry); - TestUtil.AssertUnpackedExtensionsSet(message); - } - - [Test] - public void PackedParsingOfUnpackedInputExtensions() - { - byte[] bytes = TestUnpackedTypes.ParseFrom(TestUtil.GetPackedSet().ToByteArray()).ToByteArray(); - ExtensionRegistry registry = ExtensionRegistry.CreateInstance(); - Unittest.RegisterAllExtensions(registry); - TestPackedExtensions message = TestPackedExtensions.ParseFrom(bytes, registry); - TestUtil.AssertPackedExtensionsSet(message); - } - - [Test] - public void OptimizedForSize() - { - // We're mostly only Checking that this class was compiled successfully. - TestOptimizedForSize message = TestOptimizedForSize.CreateBuilder().SetI(1).Build(); - message = TestOptimizedForSize.ParseFrom(message.ToByteString()); - Assert.AreEqual(2, message.SerializedSize); - } - - // ----------------------------------------------------------------- - // Tests for isInitialized(). - - private static readonly TestRequired TestRequiredUninitialized = TestRequired.DefaultInstance; - - private static readonly TestRequired TestRequiredInitialized = - TestRequired.CreateBuilder().SetA(1).SetB(2).SetC(3).Build(); - - [Test] - public void IsInitialized() - { - TestRequired.Builder builder = TestRequired.CreateBuilder(); - AbstractMessageWrapper.Builder abstractBuilder = new AbstractMessageWrapper.Builder(builder); - - Assert.IsFalse(abstractBuilder.IsInitialized); - builder.A = 1; - Assert.IsFalse(abstractBuilder.IsInitialized); - builder.B = 1; - Assert.IsFalse(abstractBuilder.IsInitialized); - builder.C = 1; - Assert.IsTrue(abstractBuilder.IsInitialized); - } - - [Test] - public void ForeignIsInitialized() - { - TestRequiredForeign.Builder builder = TestRequiredForeign.CreateBuilder(); - AbstractMessageWrapper.Builder abstractBuilder = new AbstractMessageWrapper.Builder(builder); - - Assert.IsTrue(abstractBuilder.IsInitialized); - - builder.SetOptionalMessage(TestRequiredUninitialized); - Assert.IsFalse(abstractBuilder.IsInitialized); - - builder.SetOptionalMessage(TestRequiredInitialized); - Assert.IsTrue(abstractBuilder.IsInitialized); - - builder.AddRepeatedMessage(TestRequiredUninitialized); - Assert.IsFalse(abstractBuilder.IsInitialized); - - builder.SetRepeatedMessage(0, TestRequiredInitialized); - Assert.IsTrue(abstractBuilder.IsInitialized); - } - - // ----------------------------------------------------------------- - // Tests for mergeFrom - - private static readonly TestAllTypes MergeSource = TestAllTypes.CreateBuilder() - .SetOptionalInt32(1) - .SetOptionalString("foo") - .SetOptionalForeignMessage(ForeignMessage.DefaultInstance) - .AddRepeatedString("bar") - .Build(); - - private static readonly TestAllTypes MergeDest = TestAllTypes.CreateBuilder() - .SetOptionalInt64(2) - .SetOptionalString("baz") - .SetOptionalForeignMessage(ForeignMessage.CreateBuilder().SetC(3).Build()) - .AddRepeatedString("qux") - .Build(); - - private const string MergeResultText = "optional_int32: 1\n" + - "optional_int64: 2\n" + - "optional_string: \"foo\"\n" + - "optional_foreign_message {\n" + - " c: 3\n" + - "}\n" + - "repeated_string: \"qux\"\n" + - "repeated_string: \"bar\"\n"; - - [Test] - public void MergeFrom() - { - AbstractMessageWrapper result = (AbstractMessageWrapper) - new AbstractMessageWrapper.Builder(TestAllTypes.CreateBuilder(MergeDest)) - .MergeFrom(MergeSource) - .Build(); - - Assert.AreEqual(MergeResultText, result.ToString()); - } - - // ----------------------------------------------------------------- - // Tests for equals and hashCode - - [Test] - public void EqualsAndHashCode() - { - TestAllTypes a = TestUtil.GetAllSet(); - TestAllTypes b = TestAllTypes.CreateBuilder().Build(); - TestAllTypes c = TestAllTypes.CreateBuilder(b).AddRepeatedString("x").Build(); - TestAllTypes d = TestAllTypes.CreateBuilder(c).AddRepeatedString("y").Build(); - TestAllExtensions e = TestUtil.GetAllExtensionsSet(); - TestAllExtensions f = TestAllExtensions.CreateBuilder(e) - .AddExtension(Unittest.RepeatedInt32Extension, 999).Build(); - - CheckEqualsIsConsistent(a); - CheckEqualsIsConsistent(b); - CheckEqualsIsConsistent(c); - CheckEqualsIsConsistent(d); - CheckEqualsIsConsistent(e); - CheckEqualsIsConsistent(f); - - CheckNotEqual(a, b); - CheckNotEqual(a, c); - CheckNotEqual(a, d); - CheckNotEqual(a, e); - CheckNotEqual(a, f); - - CheckNotEqual(b, c); - CheckNotEqual(b, d); - CheckNotEqual(b, e); - CheckNotEqual(b, f); - - CheckNotEqual(c, d); - CheckNotEqual(c, e); - CheckNotEqual(c, f); - - CheckNotEqual(d, e); - CheckNotEqual(d, f); - - CheckNotEqual(e, f); - - // Deserializing into the TestEmptyMessage such that every field is an UnknownFieldSet.Field - TestEmptyMessage eUnknownFields = TestEmptyMessage.ParseFrom(e.ToByteArray()); - TestEmptyMessage fUnknownFields = TestEmptyMessage.ParseFrom(f.ToByteArray()); - CheckNotEqual(eUnknownFields, fUnknownFields); - CheckEqualsIsConsistent(eUnknownFields); - CheckEqualsIsConsistent(fUnknownFields); - - // Subseqent reconstitutions should be identical - TestEmptyMessage eUnknownFields2 = TestEmptyMessage.ParseFrom(e.ToByteArray()); - CheckEqualsIsConsistent(eUnknownFields, eUnknownFields2); - } - - /// - /// Asserts that the given protos are equal and have the same hash code. - /// - private static void CheckEqualsIsConsistent(IMessage message) - { - // Object should be equal to itself. - Assert.AreEqual(message, message); - - // Object should be equal to a dynamic copy of itself. - DynamicMessage dynamic = DynamicMessage.CreateBuilder(message).Build(); - CheckEqualsIsConsistent(message, dynamic); - } - - /// - /// Asserts that the given protos are equal and have the same hash code. - /// - private static void CheckEqualsIsConsistent(IMessage message1, IMessage message2) - { - // Not using Assert.AreEqual as that checks for type equality, which isn't - // what we want bearing in mind the dynamic message checks. - Assert.IsTrue(message1.Equals(message2)); - Assert.IsTrue(message2.Equals(message1)); - Assert.AreEqual(message2.GetHashCode(), message1.GetHashCode()); - } - - /// - /// Asserts that the given protos are not equal and have different hash codes. - /// - /// - /// It's valid for non-equal objects to have the same hash code, so - /// this test is stricter than it needs to be. However, this should happen - /// relatively rarely. (If this test fails, it's probably still due to a bug.) - /// - private static void CheckNotEqual(IMessage m1, IMessage m2) - { - String equalsError = string.Format("{0} should not be equal to {1}", m1, m2); - Assert.IsFalse(m1.Equals(m2), equalsError); - Assert.IsFalse(m2.Equals(m1), equalsError); - - Assert.IsFalse(m1.GetHashCode() == m2.GetHashCode(), - string.Format("{0} should have a different hash code from {1}", m1, m2)); - } - - /// - /// Extends AbstractMessage and wraps some other message object. The methods - /// of the Message interface which aren't explicitly implemented by - /// AbstractMessage are forwarded to the wrapped object. This allows us to - /// test that AbstractMessage's implementations work even if the wrapped - /// object does not use them. - /// - private class AbstractMessageWrapper : AbstractMessage - { - private readonly IMessage wrappedMessage; - - public IMessage WrappedMessage - { - get { return wrappedMessage; } - } - - public AbstractMessageWrapper(IMessage wrappedMessage) - { - this.wrappedMessage = wrappedMessage; - } - - public override MessageDescriptor DescriptorForType - { - get { return wrappedMessage.DescriptorForType; } - } - - public override AbstractMessageWrapper DefaultInstanceForType - { - get { return new AbstractMessageWrapper(wrappedMessage.WeakDefaultInstanceForType); } - } - - public override IDictionary AllFields - { - get { return wrappedMessage.AllFields; } - } - - public override bool HasField(FieldDescriptor field) - { - return wrappedMessage.HasField(field); - } - - public override bool HasOneof(OneofDescriptor oneof) - { - return wrappedMessage.HasOneof(oneof); - } - - public override FieldDescriptor OneofFieldDescriptor(OneofDescriptor oneof) - { - return wrappedMessage.OneofFieldDescriptor(oneof); - } - - public override object this[FieldDescriptor field] - { - get { return wrappedMessage[field]; } - } - - public override object this[FieldDescriptor field, int index] - { - get { return wrappedMessage[field, index]; } - } - - public override int GetRepeatedFieldCount(FieldDescriptor field) - { - return wrappedMessage.GetRepeatedFieldCount(field); - } - - public override UnknownFieldSet UnknownFields - { - get { return wrappedMessage.UnknownFields; } - } - - public override Builder CreateBuilderForType() - { - return new Builder(wrappedMessage.WeakCreateBuilderForType()); - } - - public override Builder ToBuilder() - { - return new Builder(wrappedMessage.WeakToBuilder()); - } - - internal class Builder : AbstractBuilder - { - private readonly IBuilder wrappedBuilder; - - protected override Builder ThisBuilder - { - get { return this; } - } - - internal Builder(IBuilder wrappedBuilder) - { - this.wrappedBuilder = wrappedBuilder; - } - - public override Builder MergeFrom(AbstractMessageWrapper other) - { - wrappedBuilder.WeakMergeFrom(other.wrappedMessage); - return this; - } - - public override bool IsInitialized - { - get { return wrappedBuilder.IsInitialized; } - } - - public override IDictionary AllFields - { - get { return wrappedBuilder.AllFields; } - } - - public override object this[FieldDescriptor field] - { - get { return wrappedBuilder[field]; } - set { wrappedBuilder[field] = value; } - } - - public override MessageDescriptor DescriptorForType - { - get { return wrappedBuilder.DescriptorForType; } - } - - public override int GetRepeatedFieldCount(FieldDescriptor field) - { - return wrappedBuilder.GetRepeatedFieldCount(field); - } - - public override object this[FieldDescriptor field, int index] - { - get { return wrappedBuilder[field, index]; } - set { wrappedBuilder[field, index] = value; } - } - - public override bool HasField(FieldDescriptor field) - { - return wrappedBuilder.HasField(field); - } - - public override bool HasOneof(OneofDescriptor oneof) - { - return wrappedBuilder.HasOneof(oneof); - } - - public override FieldDescriptor OneofFieldDescriptor(OneofDescriptor oneof) - { - return wrappedBuilder.OneofFieldDescriptor(oneof); - } - - public override UnknownFieldSet UnknownFields - { - get { return wrappedBuilder.UnknownFields; } - set { wrappedBuilder.UnknownFields = value; } - } - - public override AbstractMessageWrapper Build() - { - return new AbstractMessageWrapper(wrappedBuilder.WeakBuild()); - } - - public override AbstractMessageWrapper BuildPartial() - { - return new AbstractMessageWrapper(wrappedBuilder.WeakBuildPartial()); - } - - public override Builder Clone() - { - return new Builder(wrappedBuilder.WeakClone()); - } - - public override AbstractMessageWrapper DefaultInstanceForType - { - get { return new AbstractMessageWrapper(wrappedBuilder.WeakDefaultInstanceForType); } - } - - public override Builder ClearField(FieldDescriptor field) - { - wrappedBuilder.WeakClearField(field); - return this; - } - - public override Builder ClearOneof(OneofDescriptor oneof) - { - wrappedBuilder.WeakClearOneof(oneof); - return this; - } - - public override Builder AddRepeatedField(FieldDescriptor field, object value) - { - wrappedBuilder.WeakAddRepeatedField(field, value); - return this; - } - - public override IBuilder CreateBuilderForField(FieldDescriptor field) - { - wrappedBuilder.CreateBuilderForField(field); - return this; - } - - public override Builder MergeFrom(IMessage other) - { - wrappedBuilder.WeakMergeFrom(other); - return this; - } - - public override Builder MergeFrom(ICodedInputStream input, ExtensionRegistry extensionRegistry) - { - wrappedBuilder.WeakMergeFrom(input, extensionRegistry); - return this; - } - } - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers.Test/ByteStringTest.cs b/csharp/src/ProtocolBuffers.Test/ByteStringTest.cs index e4f7bd9e..0edd149b 100644 --- a/csharp/src/ProtocolBuffers.Test/ByteStringTest.cs +++ b/csharp/src/ProtocolBuffers.Test/ByteStringTest.cs @@ -38,7 +38,7 @@ using System; using System.Text; using NUnit.Framework; -namespace Google.ProtocolBuffers +namespace Google.Protobuf { public class ByteStringTest { diff --git a/csharp/src/ProtocolBuffers.Test/CodedInputStreamTest.cs b/csharp/src/ProtocolBuffers.Test/CodedInputStreamTest.cs index 9bb8ba27..57650049 100644 --- a/csharp/src/ProtocolBuffers.Test/CodedInputStreamTest.cs +++ b/csharp/src/ProtocolBuffers.Test/CodedInputStreamTest.cs @@ -37,11 +37,12 @@ using System; using System.Collections.Generic; using System.IO; -using Google.ProtocolBuffers.Descriptors; -using Google.ProtocolBuffers.TestProtos; +using Google.Protobuf.Collections; +using Google.Protobuf.Descriptors; +using Google.Protobuf.TestProtos; using NUnit.Framework; -namespace Google.ProtocolBuffers +namespace Google.Protobuf { public class CodedInputStreamTest { @@ -231,7 +232,7 @@ namespace Google.ProtocolBuffers Assert.AreEqual(0x7FFFFFFFFFFFFFFFL, CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFEL)); Assert.AreEqual(unchecked((long) 0x8000000000000000L), CodedInputStream.DecodeZigZag64(0xFFFFFFFFFFFFFFFFL)); } - + /* [Test] public void ReadWholeMessage() { @@ -273,7 +274,7 @@ namespace Google.ProtocolBuffers unknownFields.MergeFieldFrom(tag, input1); input2.SkipField(); } - } + }*/ /// /// Test that a bug in SkipRawBytes has been fixed: if the skip @@ -290,7 +291,7 @@ namespace Google.ProtocolBuffers input.PopLimit(limit); Assert.AreEqual(2, input.ReadRawByte()); } - + /* public void ReadHugeBlob() { // Allocate and initialize a 1MB blob. @@ -318,7 +319,7 @@ namespace Google.ProtocolBuffers .SetOptionalBytes(TestUtil.GetAllSet().OptionalBytes) .Build(); TestUtil.AssertAllFieldsSet(message3); - } + }*/ [Test] public void ReadMaliciouslyLargeBlob() @@ -348,12 +349,11 @@ namespace Google.ProtocolBuffers { if (depth == 0) { - return TestRecursiveMessage.CreateBuilder().SetI(5).Build(); + return new TestRecursiveMessage { I = 5 }; } else { - return TestRecursiveMessage.CreateBuilder() - .SetA(MakeRecursiveMessage(depth - 1)).Build(); + return new TestRecursiveMessage { A = MakeRecursiveMessage(depth - 1) }; } } @@ -361,12 +361,12 @@ namespace Google.ProtocolBuffers { if (depth == 0) { - Assert.IsFalse(message.HasA); + Assert.IsNull(message.A); Assert.AreEqual(5, message.I); } else { - Assert.IsTrue(message.HasA); + Assert.IsNotNull(message.A); AssertMessageDepth(message.A, depth - 1); } } @@ -377,15 +377,16 @@ namespace Google.ProtocolBuffers ByteString data64 = MakeRecursiveMessage(64).ToByteString(); ByteString data65 = MakeRecursiveMessage(65).ToByteString(); - AssertMessageDepth(TestRecursiveMessage.ParseFrom(data64), 64); + AssertMessageDepth(TestRecursiveMessage.Parser.ParseFrom(data64), 64); - Assert.Throws(() => TestRecursiveMessage.ParseFrom(data65)); + Assert.Throws(() => TestRecursiveMessage.Parser.ParseFrom(data65)); CodedInputStream input = data64.CreateCodedInput(); input.SetRecursionLimit(8); - Assert.Throws(() => TestRecursiveMessage.ParseFrom(input)); + Assert.Throws(() => TestRecursiveMessage.Parser.ParseFrom(input)); } + /* [Test] public void SizeLimit() { @@ -396,7 +397,7 @@ namespace Google.ProtocolBuffers input.SetSizeLimit(16); Assert.Throws(() => TestAllTypes.ParseFrom(input)); - } + }*/ [Test] public void ResetSizeCounter() @@ -465,17 +466,16 @@ namespace Google.ProtocolBuffers } } - enum TestNegEnum { None = 0, Value = -2 } + enum TestNegEnum : long { None = 0, Value = -2 } [Test] public void TestNegativeEnum() { byte[] bytes = new byte[10] { 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01 }; CodedInputStream input = CodedInputStream.CreateInstance(bytes); - object unk; TestNegEnum val = TestNegEnum.None; - Assert.IsTrue(input.ReadEnum(ref val, out unk)); + Assert.IsTrue(input.ReadEnum(ref val)); Assert.IsTrue(input.IsAtEnd); Assert.AreEqual(TestNegEnum.Value, val); } @@ -487,7 +487,7 @@ namespace Google.ProtocolBuffers int msgSize = 1 + 1 + arraySize; byte[] bytes = new byte[msgSize]; CodedOutputStream output = CodedOutputStream.CreateInstance(bytes); - output.WritePackedInt32Array(8, "", arraySize, new int[] { 0, -1, -2, -3, -4, -5 }); + output.WritePackedInt32Array(8, "", new RepeatedField { 0, -1, -2, -3, -4, -5 }); Assert.AreEqual(0, output.SpaceLeft); @@ -497,15 +497,12 @@ namespace Google.ProtocolBuffers Assert.IsTrue(input.ReadTag(out tag, out name)); List values = new List(); - ICollection unk; - input.ReadEnumArray(tag, name, values, out unk); + input.ReadEnumArray(tag, name, values); - Assert.AreEqual(2, values.Count); + Assert.AreEqual(6, values.Count); Assert.AreEqual(TestNegEnum.None, values[0]); - Assert.AreEqual(TestNegEnum.Value, values[1]); - - Assert.NotNull(unk); - Assert.AreEqual(4, unk.Count); + Assert.AreEqual(TestNegEnum.Value, values[2]); + // TODO(jonskeet): Test unknown value preservation } [Test] @@ -515,7 +512,7 @@ namespace Google.ProtocolBuffers int msgSize = arraySize; byte[] bytes = new byte[msgSize]; CodedOutputStream output = CodedOutputStream.CreateInstance(bytes); - output.WriteInt32Array(8, "", new int[] { 0, -1, -2, -3, -4, -5 }); + output.WriteInt32Array(8, "", new RepeatedField { 0, -1, -2, -3, -4, -5 }); Assert.AreEqual(0, output.SpaceLeft); @@ -525,15 +522,12 @@ namespace Google.ProtocolBuffers Assert.IsTrue(input.ReadTag(out tag, out name)); List values = new List(); - ICollection unk; - input.ReadEnumArray(tag, name, values, out unk); + input.ReadEnumArray(tag, name, values); - Assert.AreEqual(2, values.Count); + Assert.AreEqual(6, values.Count); Assert.AreEqual(TestNegEnum.None, values[0]); - Assert.AreEqual(TestNegEnum.Value, values[1]); - - Assert.NotNull(unk); - Assert.AreEqual(4, unk.Count); + Assert.AreEqual(TestNegEnum.Value, values[2]); + // TODO(jonskeet): Test unknown value preservation } //Issue 71: CodedInputStream.ReadBytes go to slow path unnecessarily diff --git a/csharp/src/ProtocolBuffers.Test/CodedOutputStreamTest.cs b/csharp/src/ProtocolBuffers.Test/CodedOutputStreamTest.cs index 4d5b8302..df80b3af 100644 --- a/csharp/src/ProtocolBuffers.Test/CodedOutputStreamTest.cs +++ b/csharp/src/ProtocolBuffers.Test/CodedOutputStreamTest.cs @@ -37,10 +37,10 @@ using System; using System.Collections.Generic; using System.IO; -using Google.ProtocolBuffers.TestProtos; +using Google.Protobuf.Collections; using NUnit.Framework; -namespace Google.ProtocolBuffers +namespace Google.Protobuf { public class CodedOutputStreamTest { @@ -195,6 +195,7 @@ namespace Google.ProtocolBuffers 0x9abcdef012345678UL); } + /* [Test] public void WriteWholeMessage() { @@ -228,6 +229,7 @@ namespace Google.ProtocolBuffers TestUtil.AssertEqualBytes(TestUtil.GetGoldenPackedFieldsMessage().ToByteArray(), rawBytes); } + */ [Test] public void EncodeZigZag32() @@ -294,25 +296,27 @@ namespace Google.ProtocolBuffers public void TestNegativeEnumNoTag() { Assert.AreEqual(10, CodedOutputStream.ComputeInt32SizeNoTag(-2)); - Assert.AreEqual(10, CodedOutputStream.ComputeEnumSizeNoTag(-2)); + Assert.AreEqual(10, CodedOutputStream.ComputeEnumSizeNoTag(TestNegEnum.Value)); byte[] bytes = new byte[10]; CodedOutputStream output = CodedOutputStream.CreateInstance(bytes); - output.WriteEnumNoTag(-2); + output.WriteEnumNoTag(TestNegEnum.Value); Assert.AreEqual(0, output.SpaceLeft); Assert.AreEqual("FE-FF-FF-FF-FF-FF-FF-FF-FF-01", BitConverter.ToString(bytes)); } + enum TestNegEnum : long { None = 0, Value = -2 } + [Test] public void TestNegativeEnumWithTag() { Assert.AreEqual(11, CodedOutputStream.ComputeInt32Size(8, -2)); - Assert.AreEqual(11, CodedOutputStream.ComputeEnumSize(8, -2)); + Assert.AreEqual(11, CodedOutputStream.ComputeEnumSize(8, TestNegEnum.Value)); byte[] bytes = new byte[11]; CodedOutputStream output = CodedOutputStream.CreateInstance(bytes); - output.WriteEnum(8, "", -2, -2); + output.WriteEnum(8, "", TestNegEnum.Value); Assert.AreEqual(0, output.SpaceLeft); //fyi, 0x40 == 0x08 << 3 + 0, field num + wire format shift @@ -326,7 +330,8 @@ namespace Google.ProtocolBuffers int msgSize = 1 + 1 + arraySize; byte[] bytes = new byte[msgSize]; CodedOutputStream output = CodedOutputStream.CreateInstance(bytes); - output.WritePackedEnumArray(8, "", arraySize, new int[] { 0, -1, -2, -3, -4, -5 }); + output.WritePackedEnumArray(8, "", new RepeatedField { + 0, (TestNegEnum) (-1), TestNegEnum.Value, (TestNegEnum) (-3), (TestNegEnum) (-4), (TestNegEnum) (-5) }); Assert.AreEqual(0, output.SpaceLeft); @@ -350,8 +355,8 @@ namespace Google.ProtocolBuffers int msgSize = arraySize; byte[] bytes = new byte[msgSize]; CodedOutputStream output = CodedOutputStream.CreateInstance(bytes); - output.WriteEnumArray(8, "", new int[] { 0, -1, -2, -3, -4, -5 }); - + output.WriteEnumArray(8, "", new RepeatedField { + 0, (TestNegEnum) (-1), TestNegEnum.Value, (TestNegEnum) (-3), (TestNegEnum) (-4), (TestNegEnum) (-5) }); Assert.AreEqual(0, output.SpaceLeft); CodedInputStream input = CodedInputStream.CreateInstance(bytes); diff --git a/csharp/src/ProtocolBuffers.Test/Collections/PopsicleListTest.cs b/csharp/src/ProtocolBuffers.Test/Collections/PopsicleListTest.cs deleted file mode 100644 index f336a84b..00000000 --- a/csharp/src/ProtocolBuffers.Test/Collections/PopsicleListTest.cs +++ /dev/null @@ -1,125 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using NUnit.Framework; - -namespace Google.ProtocolBuffers.Collections -{ - public class PopsicleListTest - { - [Test] - public void MutatingOperationsOnFrozenList() - { - PopsicleList list = new PopsicleList(); - list.MakeReadOnly(); - Assert.Throws(() => list.Add("")); - Assert.Throws(() => list.Clear()); - Assert.Throws(() => list.Insert(0, "")); - Assert.Throws(() => list.Remove("")); - Assert.Throws(() => list.RemoveAt(0)); - Assert.Throws(() => list.Add(new[] { "", "" })); - } - - [Test] - public void NonMutatingOperationsOnFrozenList() - { - PopsicleList list = new PopsicleList(); - list.MakeReadOnly(); - Assert.IsFalse(list.Contains("")); - Assert.AreEqual(0, list.Count); - list.CopyTo(new string[5], 0); - list.GetEnumerator(); - Assert.AreEqual(-1, list.IndexOf("")); - Assert.IsTrue(list.IsReadOnly); - } - - [Test] - public void MutatingOperationsOnFluidList() - { - PopsicleList list = new PopsicleList(); - list.Add(""); - list.Clear(); - list.Insert(0, ""); - list.Remove(""); - list.Add("x"); // Just to make the next call valid - list.RemoveAt(0); - } - - [Test] - public void NonMutatingOperationsOnFluidList() - { - PopsicleList list = new PopsicleList(); - Assert.IsFalse(list.Contains("")); - Assert.AreEqual(0, list.Count); - list.CopyTo(new string[5], 0); - list.GetEnumerator(); - Assert.AreEqual(-1, list.IndexOf("")); - Assert.IsFalse(list.IsReadOnly); - } - - [Test] - public void DoesNotAddNullEnumerable() - { - PopsicleList list = new PopsicleList(); - Assert.Throws(() => list.Add((IEnumerable) null)); - } - - [Test] - public void DoesNotAddRangeWithNull() - { - PopsicleList list = new PopsicleList(); - // TODO(jonskeet): Change to ArgumentException? The argument isn't null... - Assert.Throws(() => list.Add(new[] {"a", "b", null})); - } - - [Test] - public void DoesNotAddNull() - { - PopsicleList list = new PopsicleList(); - Assert.Throws(() => list.Add((string) null)); - } - - [Test] - public void DoesNotSetNull() - { - PopsicleList list = new PopsicleList(); - list.Add("a"); - Assert.Throws(() => list[0] = null); - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers.Test/Compatibility/BinaryCompatibilityTests.cs b/csharp/src/ProtocolBuffers.Test/Compatibility/BinaryCompatibilityTests.cs deleted file mode 100644 index 30d257ad..00000000 --- a/csharp/src/ProtocolBuffers.Test/Compatibility/BinaryCompatibilityTests.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; - -namespace Google.ProtocolBuffers.Compatibility -{ - public class BinaryCompatibilityTests : CompatibilityTests - { - protected override object SerializeMessage(TMessage message) - { - byte[] bresult = message.ToByteArray(); - return Convert.ToBase64String(bresult); - } - - protected override TBuilder DeserializeMessage(object message, TBuilder builder, ExtensionRegistry registry) - { - return builder.MergeFrom((byte[])Convert.FromBase64String((string)message), registry); - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers.Test/Compatibility/CompatibilityTests.cs b/csharp/src/ProtocolBuffers.Test/Compatibility/CompatibilityTests.cs deleted file mode 100644 index a050827e..00000000 --- a/csharp/src/ProtocolBuffers.Test/Compatibility/CompatibilityTests.cs +++ /dev/null @@ -1,227 +0,0 @@ -using System; -using Google.ProtocolBuffers.TestProtos; -using NUnit.Framework; - - -namespace Google.ProtocolBuffers.Compatibility -{ - /// - /// This abstract base implements several tests to ensure that well-known messages can be written - /// and read to/from various formats without losing data. Implementations override the two serialization - /// methods to provide the tests with the means to read and write for a given format. - /// - public abstract class CompatibilityTests - { - protected abstract object SerializeMessage(TMessage message) - where TMessage : IMessageLite - where TBuilder : IBuilderLite; - - protected abstract TBuilder DeserializeMessage(object message, TBuilder builder, ExtensionRegistry registry) - where TMessage : IMessageLite - where TBuilder : IBuilderLite; - - protected virtual void AssertOutputEquals(object lhs, object rhs) - { - Assert.AreEqual(lhs, rhs); - } - - [Test] - public virtual void RoundTripWithEmptyChildMessageSize() - { - SizeMessage1 msg = SizeMessage1.CreateBuilder() - .SetField100(100) - .SetField15(SizeMessage1SubMessage.DefaultInstance) - .BuildPartial(); - byte[] contents = msg.ToByteArray(); - object content = SerializeMessage(msg); - - SizeMessage1 copy = DeserializeMessage(content, SizeMessage1.CreateBuilder(), ExtensionRegistry.Empty).BuildPartial(); - - Assert.AreEqual(msg, copy); - AssertOutputEquals(content, SerializeMessage(copy)); - Assert.AreEqual(Convert.ToBase64String(contents), Convert.ToBase64String(copy.ToByteArray())); - } - - [Test] - public virtual void RoundTripWithEmptyChildMessageSpeed() - { - SpeedMessage1 msg = SpeedMessage1.CreateBuilder() - .SetField100(100) - .SetField15(SpeedMessage1SubMessage.DefaultInstance) - .BuildPartial(); - byte[] contents = msg.ToByteArray(); - object content = SerializeMessage(msg); - - SpeedMessage1 copy = DeserializeMessage(content, SpeedMessage1.CreateBuilder(), ExtensionRegistry.Empty).BuildPartial(); - - Assert.AreEqual(msg, copy); - AssertOutputEquals(content, SerializeMessage(copy)); - Assert.AreEqual(Convert.ToBase64String(contents), Convert.ToBase64String(copy.ToByteArray())); - } - - [Test] - public virtual void RoundTripMessage1OptimizeSize() - { - SizeMessage1 msg = SizeMessage1.CreateBuilder().MergeFrom(TestResources.google_message1).Build(); - object content = SerializeMessage(msg); - - SizeMessage1 copy = DeserializeMessage(content, SizeMessage1.CreateBuilder(), ExtensionRegistry.Empty).Build(); - - Assert.AreEqual(msg, copy); - AssertOutputEquals(content, SerializeMessage(copy)); - Assert.AreEqual(Convert.ToBase64String(TestResources.google_message1), Convert.ToBase64String(copy.ToByteArray())); - } - - [Test] - public virtual void RoundTripMessage2OptimizeSize() - { - SizeMessage2 msg = SizeMessage2.CreateBuilder().MergeFrom(TestResources.google_message2).Build(); - object content = SerializeMessage(msg); - - SizeMessage2 copy = DeserializeMessage(content, SizeMessage2.CreateBuilder(), ExtensionRegistry.Empty).Build(); - - Assert.AreEqual(msg, copy); - AssertOutputEquals(content, SerializeMessage(copy)); - Assert.AreEqual(Convert.ToBase64String(TestResources.google_message2), Convert.ToBase64String(copy.ToByteArray())); - } - - [Test] - public virtual void RoundTripMessage1OptimizeSpeed() - { - SpeedMessage1 msg = SpeedMessage1.CreateBuilder().MergeFrom(TestResources.google_message1).Build(); - object content = SerializeMessage(msg); - - SpeedMessage1 copy = DeserializeMessage(content, SpeedMessage1.CreateBuilder(), ExtensionRegistry.Empty).Build(); - - Assert.AreEqual(msg, copy); - AssertOutputEquals(content, SerializeMessage(copy)); - Assert.AreEqual(Convert.ToBase64String(TestResources.google_message1), Convert.ToBase64String(copy.ToByteArray())); - } - - [Test] - public virtual void RoundTripMessage2OptimizeSpeed() - { - SpeedMessage2 msg = SpeedMessage2.CreateBuilder().MergeFrom(TestResources.google_message2).Build(); - object content = SerializeMessage(msg); - - SpeedMessage2 copy = DeserializeMessage(content, SpeedMessage2.CreateBuilder(), ExtensionRegistry.Empty).Build(); - - Assert.AreEqual(msg, copy); - AssertOutputEquals(content, SerializeMessage(copy)); - Assert.AreEqual(Convert.ToBase64String(TestResources.google_message2), Convert.ToBase64String(copy.ToByteArray())); - } - - #region Test message builders - - protected static TestAllTypes.Builder AddAllTypes(TestAllTypes.Builder builder) - { - return builder.SetOptionalInt32(1001) - .SetOptionalInt64(1001) - .SetOptionalUint32(1001) - .SetOptionalUint64(1001) - .SetOptionalSint32(-1001) - .SetOptionalSint64(-1001) - .SetOptionalFixed32(1001) - .SetOptionalFixed64(1001) - .SetOptionalSfixed32(-1001) - .SetOptionalSfixed64(-1001) - .SetOptionalFloat(1001.1001f) - .SetOptionalDouble(1001.1001) - .SetOptionalBool(true) - .SetOptionalString("this is a string value") - .SetOptionalBytes(ByteString.CopyFromUtf8("this is an array of bytes")) - .SetOptionalGroup(new TestAllTypes.Types.OptionalGroup.Builder().SetA(1001)) - .SetOptionalNestedMessage(new TestAllTypes.Types.NestedMessage.Builder().SetBb(1001)) - .SetOptionalNestedEnum(TestAllTypes.Types.NestedEnum.FOO) - ; - } - - protected static TestAllTypes.Builder AddRepeatedTypes(TestAllTypes.Builder builder, int size) - { - //repeated values - for (int i = 0; i < size; i++) - builder.AddRepeatedInt32(1001 + i) - .AddRepeatedInt64(1001) - .AddRepeatedUint32(1001) - .AddRepeatedUint64(1001) - .AddRepeatedSint32(-1001) - .AddRepeatedSint64(-1001) - .AddRepeatedFixed32(1001) - .AddRepeatedFixed64(1001) - .AddRepeatedSfixed32(-1001) - .AddRepeatedSfixed64(-1001) - .AddRepeatedFloat(1001.1001f) - .AddRepeatedDouble(1001.1001) - .AddRepeatedBool(true) - .AddRepeatedString("this is a string value") - .AddRepeatedBytes(ByteString.CopyFromUtf8("this is an array of bytes")) - .AddRepeatedGroup(new TestAllTypes.Types.RepeatedGroup.Builder().SetA(1001)) - .AddRepeatedNestedMessage(new TestAllTypes.Types.NestedMessage.Builder().SetBb(1001)) - .AddRepeatedNestedEnum(TestAllTypes.Types.NestedEnum.FOO) - ; - return builder; - } - - protected static TestPackedTypes.Builder AddPackedTypes(TestPackedTypes.Builder builder, int size) - { - for(int i=0; i < size; i++ ) - builder.AddPackedInt32(1001) - .AddPackedInt64(1001) - .AddPackedUint32(1001) - .AddPackedUint64(1001) - .AddPackedSint32(-1001) - .AddPackedSint64(-1001) - .AddPackedFixed32(1001) - .AddPackedFixed64(1001) - .AddPackedSfixed32(-1001) - .AddPackedSfixed64(-1001) - .AddPackedFloat(1001.1001f) - .AddPackedDouble(1001.1001) - .AddPackedBool(true) - .AddPackedEnum(ForeignEnum.FOREIGN_FOO) - ; - return builder; - } - - #endregion - - [Test] - public void TestRoundTripAllTypes() - { - TestAllTypes msg = AddAllTypes(new TestAllTypes.Builder()).Build(); - object content = SerializeMessage(msg); - - TestAllTypes copy = DeserializeMessage(content, TestAllTypes.CreateBuilder(), ExtensionRegistry.Empty).Build(); - - Assert.AreEqual(msg, copy); - AssertOutputEquals(content, SerializeMessage(copy)); - Assert.AreEqual(Convert.ToBase64String(msg.ToByteArray()), Convert.ToBase64String(copy.ToByteArray())); - } - - [Test] - public void TestRoundTripRepeatedTypes() - { - TestAllTypes msg = AddRepeatedTypes(new TestAllTypes.Builder(), 5).Build(); - object content = SerializeMessage(msg); - - TestAllTypes copy = DeserializeMessage(content, TestAllTypes.CreateBuilder(), ExtensionRegistry.Empty).Build(); - - Assert.AreEqual(msg, copy); - AssertOutputEquals(content, SerializeMessage(copy)); - Assert.AreEqual(Convert.ToBase64String(msg.ToByteArray()), Convert.ToBase64String(copy.ToByteArray())); - } - - [Test] - public void TestRoundTripPackedTypes() - { - TestPackedTypes msg = AddPackedTypes(new TestPackedTypes.Builder(), 5).Build(); - object content = SerializeMessage(msg); - - TestPackedTypes copy = DeserializeMessage(content, TestPackedTypes.CreateBuilder(), ExtensionRegistry.Empty).Build(); - - Assert.AreEqual(msg, copy); - AssertOutputEquals(content, SerializeMessage(copy)); - Assert.AreEqual(Convert.ToBase64String(msg.ToByteArray()), Convert.ToBase64String(copy.ToByteArray())); - } - } -} diff --git a/csharp/src/ProtocolBuffers.Test/Compatibility/DictionaryCompatibilityTests.cs b/csharp/src/ProtocolBuffers.Test/Compatibility/DictionaryCompatibilityTests.cs deleted file mode 100644 index 299bb1a6..00000000 --- a/csharp/src/ProtocolBuffers.Test/Compatibility/DictionaryCompatibilityTests.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System; -using System.Collections.Generic; -using Google.ProtocolBuffers.Serialization; -using NUnit.Framework; - -namespace Google.ProtocolBuffers.Compatibility -{ - [TestFixture] - public class DictionaryCompatibilityTests : CompatibilityTests - { - protected override object SerializeMessage(TMessage message) - { - DictionaryWriter writer = new DictionaryWriter(); - writer.WriteMessage(message); - return writer.ToDictionary(); - } - - protected override TBuilder DeserializeMessage(object message, TBuilder builder, ExtensionRegistry registry) - { - new DictionaryReader((IDictionary)message).Merge(builder); - return builder; - } - - protected override void AssertOutputEquals(object lhs, object rhs) - { - IDictionary left = (IDictionary)lhs; - IDictionary right = (IDictionary)rhs; - - Assert.AreEqual( - String.Join(",", new List(left.Keys).ToArray()), - String.Join(",", new List(right.Keys).ToArray()) - ); - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers.Test/Compatibility/JsonCompatibilityTests.cs b/csharp/src/ProtocolBuffers.Test/Compatibility/JsonCompatibilityTests.cs deleted file mode 100644 index a1e0ed33..00000000 --- a/csharp/src/ProtocolBuffers.Test/Compatibility/JsonCompatibilityTests.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System.IO; -using Google.ProtocolBuffers.Serialization; -using NUnit.Framework; - -namespace Google.ProtocolBuffers.Compatibility -{ - [TestFixture] - public class JsonCompatibilityTests : CompatibilityTests - { - protected override object SerializeMessage(TMessage message) - { - StringWriter sw = new StringWriter(); - JsonFormatWriter.CreateInstance(sw) - .WriteMessage(message); - return sw.ToString(); - } - - protected override TBuilder DeserializeMessage(object message, TBuilder builder, ExtensionRegistry registry) - { - JsonFormatReader.CreateInstance((string)message).Merge(builder); - return builder; - } - } - - [TestFixture] - public class JsonCompatibilityFormattedTests : CompatibilityTests - { - protected override object SerializeMessage(TMessage message) - { - StringWriter sw = new StringWriter(); - JsonFormatWriter.CreateInstance(sw) - .Formatted() - .WriteMessage(message); - return sw.ToString(); - } - - protected override TBuilder DeserializeMessage(object message, TBuilder builder, ExtensionRegistry registry) - { - JsonFormatReader.CreateInstance((string)message).Merge(builder); - return builder; - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers.Test/Compatibility/TestResources.cs b/csharp/src/ProtocolBuffers.Test/Compatibility/TestResources.cs deleted file mode 100644 index 2282d61f..00000000 --- a/csharp/src/ProtocolBuffers.Test/Compatibility/TestResources.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System.IO; -using NUnit.Framework; - -namespace Google.ProtocolBuffers.Compatibility -{ - static class TestResources - { - public static byte[] google_message1 - { - get - { - Stream resource = typeof(TestResources).Assembly.GetManifestResourceStream( - typeof(TestResources).Namespace + ".google_message1.dat"); - - Assert.NotNull(resource); - - byte[] bytes = new byte[resource.Length]; - int amtRead = resource.Read(bytes, 0, bytes.Length); - Assert.AreEqual(bytes.Length, amtRead); - return bytes; - } - } - public static byte[] google_message2 - { - get - { - Stream resource = typeof(TestResources).Assembly.GetManifestResourceStream( - typeof(TestResources).Namespace + ".google_message2.dat"); - - Assert.NotNull(resource); - byte[] bytes = new byte[resource.Length]; - int amtRead = resource.Read(bytes, 0, bytes.Length); - Assert.AreEqual(bytes.Length, amtRead); - return bytes; - } - } - } -} diff --git a/csharp/src/ProtocolBuffers.Test/Compatibility/TextCompatibilityTests.cs b/csharp/src/ProtocolBuffers.Test/Compatibility/TextCompatibilityTests.cs deleted file mode 100644 index 89d6e260..00000000 --- a/csharp/src/ProtocolBuffers.Test/Compatibility/TextCompatibilityTests.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System.IO; -using NUnit.Framework; - -namespace Google.ProtocolBuffers.Compatibility -{ - [TestFixture] - public class TextCompatibilityTests : CompatibilityTests - { - protected override object SerializeMessage(TMessage message) - { - StringWriter text = new StringWriter(); - message.PrintTo(text); - return text.ToString(); - } - - protected override TBuilder DeserializeMessage(object message, TBuilder builder, ExtensionRegistry registry) - { - TextFormat.Merge(new StringReader((string)message), registry, (IBuilder)builder); - return builder; - } - //This test can take a very long time to run. - [Test] - public override void RoundTripMessage2OptimizeSize() - { - //base.RoundTripMessage2OptimizeSize(); - } - - //This test can take a very long time to run. - [Test] - public override void RoundTripMessage2OptimizeSpeed() - { - //base.RoundTripMessage2OptimizeSpeed(); - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers.Test/Compatibility/XmlCompatibilityTests.cs b/csharp/src/ProtocolBuffers.Test/Compatibility/XmlCompatibilityTests.cs deleted file mode 100644 index 91d40d83..00000000 --- a/csharp/src/ProtocolBuffers.Test/Compatibility/XmlCompatibilityTests.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System.IO; -using System.Xml; -using Google.ProtocolBuffers.Serialization; -using NUnit.Framework; - -namespace Google.ProtocolBuffers.Compatibility -{ - [TestFixture] - public class XmlCompatibilityTests : CompatibilityTests - { - protected override object SerializeMessage(TMessage message) - { - StringWriter text = new StringWriter(); - XmlFormatWriter writer = XmlFormatWriter.CreateInstance(text); - writer.WriteMessage("root", message); - return text.ToString(); - } - - protected override TBuilder DeserializeMessage(object message, TBuilder builder, ExtensionRegistry registry) - { - XmlFormatReader reader = XmlFormatReader.CreateInstance((string)message); - return reader.Merge("root", builder, registry); - } - } - - [TestFixture] - public class XmlCompatibilityFormattedTests : CompatibilityTests - { - protected override object SerializeMessage(TMessage message) - { - StringWriter text = new StringWriter(); - XmlWriter xwtr = XmlWriter.Create(text, new XmlWriterSettings { Indent = true, IndentChars = " " }); - - XmlFormatWriter writer = XmlFormatWriter.CreateInstance(xwtr).SetOptions(XmlWriterOptions.OutputNestedArrays); - writer.WriteMessage("root", message); - return text.ToString(); - } - - protected override TBuilder DeserializeMessage(object message, TBuilder builder, ExtensionRegistry registry) - { - XmlFormatReader reader = XmlFormatReader.CreateInstance((string)message).SetOptions(XmlReaderOptions.ReadNestedArrays); - return reader.Merge("root", builder, registry); - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers.Test/Compatibility/google_message1.dat b/csharp/src/ProtocolBuffers.Test/Compatibility/google_message1.dat deleted file mode 100644 index bc0f064c..00000000 Binary files a/csharp/src/ProtocolBuffers.Test/Compatibility/google_message1.dat and /dev/null differ diff --git a/csharp/src/ProtocolBuffers.Test/Compatibility/google_message2.dat b/csharp/src/ProtocolBuffers.Test/Compatibility/google_message2.dat deleted file mode 100644 index 06c09441..00000000 Binary files a/csharp/src/ProtocolBuffers.Test/Compatibility/google_message2.dat and /dev/null differ diff --git a/csharp/src/ProtocolBuffers.Test/DeprecatedMemberTest.cs b/csharp/src/ProtocolBuffers.Test/DeprecatedMemberTest.cs index db64d37a..c962df54 100644 --- a/csharp/src/ProtocolBuffers.Test/DeprecatedMemberTest.cs +++ b/csharp/src/ProtocolBuffers.Test/DeprecatedMemberTest.cs @@ -1,9 +1,9 @@ using System; using System.Reflection; -using UnitTest.Issues.TestProtos; +using Google.Protobuf.TestProtos; using NUnit.Framework; -namespace Google.ProtocolBuffers +namespace Google.Protobuf { public class DeprecatedMemberTest { @@ -16,84 +16,8 @@ namespace Google.ProtocolBuffers [Test] public void TestDepreatedPrimitiveValue() { - AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("HasPrimitiveValue")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("PrimitiveValue")); - - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("HasPrimitiveValue")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("PrimitiveValue")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("ClearPrimitiveValue")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetPrimitiveValue")); - } - [Test] - public void TestDepreatedPrimitiveArray() - { - AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("PrimitiveArrayList")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("PrimitiveArrayCount")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetMethod("GetPrimitiveArray")); - - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("PrimitiveArrayList")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("PrimitiveArrayCount")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("GetPrimitiveArray")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetPrimitiveArray")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddPrimitiveArray")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddRangePrimitiveArray")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("ClearPrimitiveArray")); - } - [Test] - public void TestDepreatedMessageValue() - { - AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("HasMessageValue")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("MessageValue")); - - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("HasMessageValue")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("MessageValue")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("MergeMessageValue")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("ClearMessageValue")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetMessageValue", new[] { typeof(DeprecatedChild) })); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetMessageValue", new[] { typeof(DeprecatedChild.Builder) })); - } - [Test] - public void TestDepreatedMessageArray() - { - AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("MessageArrayList")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("MessageArrayCount")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetMethod("GetMessageArray")); - - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("MessageArrayList")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("MessageArrayCount")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("GetMessageArray")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetMessageArray", new[] { typeof(int), typeof(DeprecatedChild) })); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetMessageArray", new[] { typeof(int), typeof(DeprecatedChild.Builder) })); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddMessageArray", new[] { typeof(DeprecatedChild) })); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddMessageArray", new[] { typeof(DeprecatedChild.Builder) })); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddRangeMessageArray")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("ClearMessageArray")); - } - [Test] - public void TestDepreatedEnumValue() - { - AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("HasEnumValue")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("EnumValue")); - - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("HasEnumValue")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("EnumValue")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("ClearEnumValue")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetEnumValue")); + AssertIsDeprecated(typeof(TestDeprecatedFields).GetProperty("DeprecatedInt32")); } - [Test] - public void TestDepreatedEnumArray() - { - AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("EnumArrayList")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetProperty("EnumArrayCount")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage).GetMethod("GetEnumArray")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("EnumArrayList")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetProperty("EnumArrayCount")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("GetEnumArray")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("SetEnumArray")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddEnumArray")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("AddRangeEnumArray")); - AssertIsDeprecated(typeof(DeprecatedFieldsMessage.Builder).GetMethod("ClearEnumArray")); - } } } diff --git a/csharp/src/ProtocolBuffers.Test/DescriptorsTest.cs b/csharp/src/ProtocolBuffers.Test/DescriptorsTest.cs index 3c26f441..8c01e16a 100644 --- a/csharp/src/ProtocolBuffers.Test/DescriptorsTest.cs +++ b/csharp/src/ProtocolBuffers.Test/DescriptorsTest.cs @@ -34,11 +34,11 @@ #endregion -using Google.ProtocolBuffers.Descriptors; -using Google.ProtocolBuffers.TestProtos; +using Google.Protobuf.Descriptors; +using Google.Protobuf.TestProtos; using NUnit.Framework; -namespace Google.ProtocolBuffers +namespace Google.Protobuf { /// /// Tests for descriptors. (Not in its own namespace or broken up into individual classes as the @@ -49,21 +49,21 @@ namespace Google.ProtocolBuffers [Test] public void FileDescriptor() { - FileDescriptor file = Unittest.Descriptor; + FileDescriptor file = UnittestProto3.Descriptor; - Assert.AreEqual("google/protobuf/unittest.proto", file.Name); + Assert.AreEqual("google/protobuf/unittest_proto3.proto", file.Name); Assert.AreEqual("protobuf_unittest", file.Package); Assert.AreEqual("UnittestProto", file.Options.JavaOuterClassname); - Assert.AreEqual("google/protobuf/unittest.proto", file.Proto.Name); + Assert.AreEqual("google/protobuf/unittest_proto3.proto", file.Proto.Name); // unittest.proto doesn't have any public imports, but unittest_import.proto does. Assert.AreEqual(0, file.PublicDependencies.Count); - Assert.AreEqual(1, UnittestImport.Descriptor.PublicDependencies.Count); - Assert.AreEqual(UnittestImportPublic.Descriptor, UnittestImport.Descriptor.PublicDependencies[0]); + Assert.AreEqual(1, UnittestImportProto3.Descriptor.PublicDependencies.Count); + Assert.AreEqual(UnittestImportPublicProto3.Descriptor, UnittestImportProto3.Descriptor.PublicDependencies[0]); Assert.AreEqual(1, file.Dependencies.Count); - Assert.AreEqual(UnittestImport.Descriptor, file.Dependencies[0]); + Assert.AreEqual(UnittestImportProto3.Descriptor, file.Dependencies[0]); MessageDescriptor messageType = TestAllTypes.Descriptor; Assert.AreEqual(messageType, file.MessageTypes[0]); @@ -78,23 +78,12 @@ namespace Google.ProtocolBuffers Assert.AreEqual(file.EnumTypes[0], file.FindTypeByName("ForeignEnum")); Assert.Null(file.FindTypeByName("NoSuchType")); Assert.Null(file.FindTypeByName("protobuf_unittest.ForeignEnum")); - Assert.AreEqual(1, UnittestImport.Descriptor.EnumTypes.Count); - Assert.AreEqual("ImportEnum", UnittestImport.Descriptor.EnumTypes[0].Name); + Assert.AreEqual(1, UnittestImportProto3.Descriptor.EnumTypes.Count); + Assert.AreEqual("ImportEnum", UnittestImportProto3.Descriptor.EnumTypes[0].Name); for (int i = 0; i < file.EnumTypes.Count; i++) { Assert.AreEqual(i, file.EnumTypes[i].Index); } - - FieldDescriptor extension = Unittest.OptionalInt32Extension.Descriptor; - Assert.AreEqual(extension, file.Extensions[0]); - Assert.AreEqual(extension, file.FindTypeByName("optional_int32_extension")); - Assert.Null(file.FindTypeByName("no_such_ext")); - Assert.Null(file.FindTypeByName("protobuf_unittest.optional_int32_extension")); - Assert.AreEqual(0, UnittestImport.Descriptor.Extensions.Count); - for (int i = 0; i < file.Extensions.Count; i++) - { - Assert.AreEqual(i, file.Extensions[i].Index); - } } [Test] @@ -105,19 +94,20 @@ namespace Google.ProtocolBuffers Assert.AreEqual("TestAllTypes", messageType.Name); Assert.AreEqual("protobuf_unittest.TestAllTypes", messageType.FullName); - Assert.AreEqual(Unittest.Descriptor, messageType.File); - Assert.Null(messageType.ContainingType); - Assert.AreEqual(DescriptorProtos.MessageOptions.DefaultInstance, messageType.Options); - Assert.AreEqual("TestAllTypes", messageType.Proto.Name); + Assert.AreEqual(UnittestProto3.Descriptor, messageType.File); + Assert.IsNull(messageType.ContainingType); + Assert.IsNull(messageType.Options); + + Assert.AreEqual("TestAllTypes", messageType.Name); Assert.AreEqual("NestedMessage", nestedType.Name); Assert.AreEqual("protobuf_unittest.TestAllTypes.NestedMessage", nestedType.FullName); - Assert.AreEqual(Unittest.Descriptor, nestedType.File); + Assert.AreEqual(UnittestProto3.Descriptor, nestedType.File); Assert.AreEqual(messageType, nestedType.ContainingType); FieldDescriptor field = messageType.Fields[0]; - Assert.AreEqual("optional_int32", field.Name); - Assert.AreEqual(field, messageType.FindDescriptor("optional_int32")); + Assert.AreEqual("single_int32", field.Name); + Assert.AreEqual(field, messageType.FindDescriptor("single_int32")); Assert.Null(messageType.FindDescriptor("no_such_field")); Assert.AreEqual(field, messageType.FindFieldByNumber(1)); Assert.Null(messageType.FindFieldByNumber(571283)); @@ -146,115 +136,66 @@ namespace Google.ProtocolBuffers public void FieldDescriptor() { MessageDescriptor messageType = TestAllTypes.Descriptor; - FieldDescriptor primitiveField = messageType.FindDescriptor("optional_int32"); - FieldDescriptor enumField = messageType.FindDescriptor("optional_nested_enum"); - FieldDescriptor messageField = messageType.FindDescriptor("optional_foreign_message"); - FieldDescriptor cordField = messageType.FindDescriptor("optional_cord"); - FieldDescriptor extension = Unittest.OptionalInt32Extension.Descriptor; - FieldDescriptor nestedExtension = TestRequired.Single.Descriptor; + FieldDescriptor primitiveField = messageType.FindDescriptor("single_int32"); + FieldDescriptor enumField = messageType.FindDescriptor("single_nested_enum"); + FieldDescriptor messageField = messageType.FindDescriptor("single_foreign_message"); - Assert.AreEqual("optional_int32", primitiveField.Name); - Assert.AreEqual("protobuf_unittest.TestAllTypes.optional_int32", + Assert.AreEqual("single_int32", primitiveField.Name); + Assert.AreEqual("protobuf_unittest.TestAllTypes.single_int32", primitiveField.FullName); Assert.AreEqual(1, primitiveField.FieldNumber); Assert.AreEqual(messageType, primitiveField.ContainingType); - Assert.AreEqual(Unittest.Descriptor, primitiveField.File); + Assert.AreEqual(UnittestProto3.Descriptor, primitiveField.File); Assert.AreEqual(FieldType.Int32, primitiveField.FieldType); Assert.AreEqual(MappedType.Int32, primitiveField.MappedType); - Assert.AreEqual(DescriptorProtos.FieldOptions.DefaultInstance, primitiveField.Options); - Assert.IsFalse(primitiveField.IsExtension); - Assert.AreEqual("optional_int32", primitiveField.Proto.Name); - - Assert.AreEqual("optional_nested_enum", enumField.Name); + Assert.IsNull(primitiveField.Options); + + Assert.AreEqual("single_nested_enum", enumField.Name); Assert.AreEqual(FieldType.Enum, enumField.FieldType); Assert.AreEqual(MappedType.Enum, enumField.MappedType); // Assert.AreEqual(TestAllTypes.Types.NestedEnum.DescriptorProtoFile, enumField.EnumType); - Assert.AreEqual("optional_foreign_message", messageField.Name); + Assert.AreEqual("single_foreign_message", messageField.Name); Assert.AreEqual(FieldType.Message, messageField.FieldType); Assert.AreEqual(MappedType.Message, messageField.MappedType); Assert.AreEqual(ForeignMessage.Descriptor, messageField.MessageType); - - Assert.AreEqual("optional_cord", cordField.Name); - Assert.AreEqual(FieldType.String, cordField.FieldType); - Assert.AreEqual(MappedType.String, cordField.MappedType); - Assert.AreEqual(DescriptorProtos.FieldOptions.Types.CType.CORD, cordField.Options.Ctype); - - Assert.AreEqual("optional_int32_extension", extension.Name); - Assert.AreEqual("protobuf_unittest.optional_int32_extension", extension.FullName); - Assert.AreEqual(1, extension.FieldNumber); - Assert.AreEqual(TestAllExtensions.Descriptor, extension.ContainingType); - Assert.AreEqual(Unittest.Descriptor, extension.File); - Assert.AreEqual(FieldType.Int32, extension.FieldType); - Assert.AreEqual(MappedType.Int32, extension.MappedType); - Assert.AreEqual(DescriptorProtos.FieldOptions.DefaultInstance, - extension.Options); - Assert.IsTrue(extension.IsExtension); - Assert.AreEqual(null, extension.ExtensionScope); - Assert.AreEqual("optional_int32_extension", extension.Proto.Name); - - Assert.AreEqual("single", nestedExtension.Name); - Assert.AreEqual("protobuf_unittest.TestRequired.single", - nestedExtension.FullName); - Assert.AreEqual(TestRequired.Descriptor, - nestedExtension.ExtensionScope); } [Test] public void FieldDescriptorLabel() { - FieldDescriptor requiredField = - TestRequired.Descriptor.FindDescriptor("a"); - FieldDescriptor optionalField = - TestAllTypes.Descriptor.FindDescriptor("optional_int32"); + FieldDescriptor singleField = + TestAllTypes.Descriptor.FindDescriptor("single_int32"); FieldDescriptor repeatedField = TestAllTypes.Descriptor.FindDescriptor("repeated_int32"); - Assert.IsTrue(requiredField.IsRequired); - Assert.IsFalse(requiredField.IsRepeated); - Assert.IsFalse(optionalField.IsRequired); - Assert.IsFalse(optionalField.IsRepeated); + Assert.IsFalse(singleField.IsRequired); + Assert.IsFalse(singleField.IsRepeated); Assert.IsFalse(repeatedField.IsRequired); Assert.IsTrue(repeatedField.IsRepeated); } - [Test] - public void FieldDescriptorDefault() - { - MessageDescriptor d = TestAllTypes.Descriptor; - Assert.IsFalse(d.FindDescriptor("optional_int32").HasDefaultValue); - Assert.AreEqual(0, d.FindDescriptor("optional_int32").DefaultValue); - Assert.IsTrue(d.FindDescriptor("default_int32").HasDefaultValue); - Assert.AreEqual(41, d.FindDescriptor("default_int32").DefaultValue); - - d = TestExtremeDefaultValues.Descriptor; - Assert.AreEqual(TestExtremeDefaultValues.DefaultInstance.EscapedBytes, - d.FindDescriptor("escaped_bytes").DefaultValue); - Assert.AreEqual(uint.MaxValue, d.FindDescriptor("large_uint32").DefaultValue); - Assert.AreEqual(ulong.MaxValue, d.FindDescriptor("large_uint64").DefaultValue); - } [Test] public void EnumDescriptor() { // Note: this test is a bit different to the Java version because there's no static way of getting to the descriptor - EnumDescriptor enumType = Unittest.Descriptor.FindTypeByName("ForeignEnum"); + EnumDescriptor enumType = UnittestProto3.Descriptor.FindTypeByName("ForeignEnum"); EnumDescriptor nestedType = TestAllTypes.Descriptor.FindDescriptor("NestedEnum"); Assert.AreEqual("ForeignEnum", enumType.Name); Assert.AreEqual("protobuf_unittest.ForeignEnum", enumType.FullName); - Assert.AreEqual(Unittest.Descriptor, enumType.File); + Assert.AreEqual(UnittestProto3.Descriptor, enumType.File); Assert.Null(enumType.ContainingType); - Assert.AreEqual(DescriptorProtos.EnumOptions.DefaultInstance, - enumType.Options); + Assert.Null(enumType.Options); Assert.AreEqual("NestedEnum", nestedType.Name); Assert.AreEqual("protobuf_unittest.TestAllTypes.NestedEnum", nestedType.FullName); - Assert.AreEqual(Unittest.Descriptor, nestedType.File); + Assert.AreEqual(UnittestProto3.Descriptor, nestedType.File); Assert.AreEqual(TestAllTypes.Descriptor, nestedType.ContainingType); EnumValueDescriptor value = enumType.FindValueByName("FOREIGN_FOO"); - Assert.AreEqual(value, enumType.Values[0]); + Assert.AreEqual(value, enumType.Values[1]); Assert.AreEqual("FOREIGN_FOO", value.Name); Assert.AreEqual(4, value.Number); Assert.AreEqual((int) ForeignEnum.FOREIGN_FOO, value.Number); @@ -265,22 +206,5 @@ namespace Google.ProtocolBuffers Assert.AreEqual(i, enumType.Values[i].Index); } } - - - [Test] - public void CustomOptions() - { - MessageDescriptor descriptor = TestMessageWithCustomOptions.Descriptor; - Assert.IsTrue(descriptor.Options.HasExtension(UnittestCustomOptions.MessageOpt1)); - Assert.AreEqual(-56, descriptor.Options.GetExtension(UnittestCustomOptions.MessageOpt1)); - - - FieldDescriptor field = descriptor.FindFieldByName("field1"); - Assert.NotNull(field); - - Assert.IsTrue(field.Options.HasExtension(UnittestCustomOptions.FieldOpt1)); - Assert.AreEqual(8765432109uL, field.Options.GetExtension(UnittestCustomOptions.FieldOpt1)); - - } } } \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers.Test/DynamicMessageTest.cs b/csharp/src/ProtocolBuffers.Test/DynamicMessageTest.cs deleted file mode 100644 index f60db213..00000000 --- a/csharp/src/ProtocolBuffers.Test/DynamicMessageTest.cs +++ /dev/null @@ -1,276 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using Google.ProtocolBuffers.Descriptors; -using Google.ProtocolBuffers.TestProtos; -using NUnit.Framework; - -namespace Google.ProtocolBuffers -{ - public class DynamicMessageTest - { - private ReflectionTester reflectionTester; - private ReflectionTester extensionsReflectionTester; - private ReflectionTester packedReflectionTester; - - public DynamicMessageTest() - { - reflectionTester = ReflectionTester.CreateTestAllTypesInstance(); - extensionsReflectionTester = ReflectionTester.CreateTestAllExtensionsInstance(); - packedReflectionTester = ReflectionTester.CreateTestPackedTypesInstance(); - } - - [Test] - public void DynamicMessageAccessors() - { - IBuilder builder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor); - reflectionTester.SetAllFieldsViaReflection(builder); - IMessage message = builder.WeakBuild(); - reflectionTester.AssertAllFieldsSetViaReflection(message); - } - - [Test] - public void DoubleBuildError() - { - DynamicMessage.Builder builder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor); - builder.Build(); - Assert.Throws(() => builder.Build()); - } - - [Test] - public void DynamicMessageSettersRejectNull() - { - IBuilder builder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor); - reflectionTester.AssertReflectionSettersRejectNull(builder); - } - - [Test] - public void DynamicMessageExtensionAccessors() - { - // We don't need to extensively test DynamicMessage's handling of - // extensions because, frankly, it doesn't do anything special with them. - // It treats them just like any other fields. - IBuilder builder = DynamicMessage.CreateBuilder(TestAllExtensions.Descriptor); - extensionsReflectionTester.SetAllFieldsViaReflection(builder); - IMessage message = builder.WeakBuild(); - extensionsReflectionTester.AssertAllFieldsSetViaReflection(message); - } - - [Test] - public void DynamicMessageExtensionSettersRejectNull() - { - IBuilder builder = DynamicMessage.CreateBuilder(TestAllExtensions.Descriptor); - extensionsReflectionTester.AssertReflectionSettersRejectNull(builder); - } - - [Test] - public void DynamicMessageRepeatedSetters() - { - IBuilder builder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor); - reflectionTester.SetAllFieldsViaReflection(builder); - reflectionTester.ModifyRepeatedFieldsViaReflection(builder); - IMessage message = builder.WeakBuild(); - reflectionTester.AssertRepeatedFieldsModifiedViaReflection(message); - } - - [Test] - public void DynamicMessageRepeatedSettersRejectNull() - { - IBuilder builder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor); - reflectionTester.AssertReflectionRepeatedSettersRejectNull(builder); - } - - [Test] - public void DynamicMessageDefaults() - { - reflectionTester.AssertClearViaReflection(DynamicMessage.GetDefaultInstance(TestAllTypes.Descriptor)); - reflectionTester.AssertClearViaReflection(DynamicMessage.CreateBuilder(TestAllTypes.Descriptor).Build()); - } - - [Test] - public void DynamicMessageSerializedSize() - { - TestAllTypes message = TestUtil.GetAllSet(); - - IBuilder dynamicBuilder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor); - reflectionTester.SetAllFieldsViaReflection(dynamicBuilder); - IMessage dynamicMessage = dynamicBuilder.WeakBuild(); - - Assert.AreEqual(message.SerializedSize, dynamicMessage.SerializedSize); - } - - [Test] - public void DynamicMessageSerialization() - { - IBuilder builder = DynamicMessage.CreateBuilder(TestAllTypes.Descriptor); - reflectionTester.SetAllFieldsViaReflection(builder); - IMessage message = builder.WeakBuild(); - - ByteString rawBytes = message.ToByteString(); - TestAllTypes message2 = TestAllTypes.ParseFrom(rawBytes); - - TestUtil.AssertAllFieldsSet(message2); - - // In fact, the serialized forms should be exactly the same, byte-for-byte. - Assert.AreEqual(TestUtil.GetAllSet().ToByteString(), rawBytes); - } - - [Test] - public void DynamicMessageParsing() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - TestUtil.SetAllFields(builder); - TestAllTypes message = builder.Build(); - - ByteString rawBytes = message.ToByteString(); - - IMessage message2 = DynamicMessage.ParseFrom(TestAllTypes.Descriptor, rawBytes); - reflectionTester.AssertAllFieldsSetViaReflection(message2); - } - - [Test] - public void DynamicMessagePackedSerialization() - { - IBuilder builder = DynamicMessage.CreateBuilder(TestPackedTypes.Descriptor); - packedReflectionTester.SetPackedFieldsViaReflection(builder); - IMessage message = builder.WeakBuild(); - - ByteString rawBytes = message.ToByteString(); - TestPackedTypes message2 = TestPackedTypes.ParseFrom(rawBytes); - - TestUtil.AssertPackedFieldsSet(message2); - - // In fact, the serialized forms should be exactly the same, byte-for-byte. - Assert.AreEqual(TestUtil.GetPackedSet().ToByteString(), rawBytes); - } - - [Test] - public void DynamicMessagePackedParsing() - { - TestPackedTypes.Builder builder = TestPackedTypes.CreateBuilder(); - TestUtil.SetPackedFields(builder); - TestPackedTypes message = builder.Build(); - - ByteString rawBytes = message.ToByteString(); - - IMessage message2 = DynamicMessage.ParseFrom(TestPackedTypes.Descriptor, rawBytes); - packedReflectionTester.AssertPackedFieldsSetViaReflection(message2); - } - - [Test] - public void DynamicMessageCopy() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - TestUtil.SetAllFields(builder); - TestAllTypes message = builder.Build(); - - DynamicMessage copy = DynamicMessage.CreateBuilder(message).Build(); - reflectionTester.AssertAllFieldsSetViaReflection(copy); - - // Oneof - FieldDescriptor bytesField = - TestAllTypes.Descriptor.FindFieldByName("oneof_bytes"); - FieldDescriptor uint32Field = - TestAllTypes.Descriptor.FindFieldByName("oneof_uint32"); - Assert.True(copy.HasField(bytesField)); - Assert.False(copy.HasField(uint32Field)); - - DynamicMessage.Builder dynamicBuilder = DynamicMessage.CreateBuilder(message); - dynamicBuilder[uint32Field] = 123U; - DynamicMessage copy2 = dynamicBuilder.Build(); - Assert.IsFalse(copy2.HasField(bytesField)); - Assert.IsTrue(copy2.HasField(uint32Field)); - Assert.AreEqual(123U, copy2[uint32Field]); - } - - [Test] - public void ToBuilder() - { - DynamicMessage.Builder builder = - DynamicMessage.CreateBuilder(TestAllTypes.Descriptor); - reflectionTester.SetAllFieldsViaReflection(builder); - int unknownFieldNum = 9; - ulong unknownFieldVal = 90; - builder.SetUnknownFields(UnknownFieldSet.CreateBuilder() - .AddField(unknownFieldNum, - UnknownField.CreateBuilder().AddVarint(unknownFieldVal).Build()) - .Build()); - DynamicMessage message = builder.Build(); - - DynamicMessage derived = message.ToBuilder().Build(); - reflectionTester.AssertAllFieldsSetViaReflection(derived); - - IList values = derived.UnknownFields.FieldDictionary[unknownFieldNum].VarintList; - Assert.AreEqual(1, values.Count); - Assert.AreEqual(unknownFieldVal, values[0]); - } - - [Test] - public void DynamicOneofMessage() - { - DynamicMessage.Builder builder = - DynamicMessage.CreateBuilder(TestAllTypes.Descriptor); - OneofDescriptor oneof = TestAllTypes.Descriptor.Oneofs[0]; - Assert.False(builder.HasOneof(oneof)); - Assert.AreSame(null, builder.OneofFieldDescriptor(oneof)); - - reflectionTester.SetAllFieldsViaReflection(builder); - Assert.True(builder.HasOneof(oneof)); - FieldDescriptor field = oneof.Field(3); - Assert.AreSame(field, builder.OneofFieldDescriptor(oneof)); - Assert.AreEqual(TestUtil.ToBytes("604"), builder[field]); - - DynamicMessage message = builder.BuildPartial(); - Assert.IsTrue(message.HasOneof(oneof)); - - DynamicMessage.Builder mergedBuilder = - DynamicMessage.CreateBuilder(TestAllTypes.Descriptor); - FieldDescriptor mergedField = oneof.Field(0); - mergedBuilder[mergedField] = 123U; - Assert.IsTrue(mergedBuilder.HasField(mergedField)); - mergedBuilder.MergeFrom(message); - Assert.IsTrue(mergedBuilder.HasField(field)); - Assert.IsFalse(mergedBuilder.HasField(mergedField)); - - mergedBuilder.ClearOneof(oneof); - Assert.AreSame(null, mergedBuilder.OneofFieldDescriptor(oneof)); - message = mergedBuilder.Build(); - Assert.AreSame(null, message.OneofFieldDescriptor(oneof)); - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers.Test/ExtendableMessageTest.cs b/csharp/src/ProtocolBuffers.Test/ExtendableMessageTest.cs deleted file mode 100644 index 2aaf39c8..00000000 --- a/csharp/src/ProtocolBuffers.Test/ExtendableMessageTest.cs +++ /dev/null @@ -1,200 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using Google.ProtocolBuffers.TestProtos; -using NUnit.Framework; - -namespace Google.ProtocolBuffers -{ - public class ExtendableMessageTest - { - [Test] - public void ExtensionWriterInvalidExtension() - { - Assert.Throws(() => - TestPackedExtensions.CreateBuilder()[Unittest.OptionalForeignMessageExtension.Descriptor] = - ForeignMessage.DefaultInstance); - } - - [Test] - public void ExtensionWriterTest() - { - TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder() - .SetExtension(Unittest.DefaultBoolExtension, true) - .SetExtension(Unittest.DefaultBytesExtension, ByteString.CopyFromUtf8("123")) - .SetExtension(Unittest.DefaultCordExtension, "123") - .SetExtension(Unittest.DefaultDoubleExtension, 123) - .SetExtension(Unittest.DefaultFixed32Extension, 123u) - .SetExtension(Unittest.DefaultFixed64Extension, 123u) - .SetExtension(Unittest.DefaultFloatExtension, 123) - .SetExtension(Unittest.DefaultForeignEnumExtension, ForeignEnum.FOREIGN_BAZ) - .SetExtension(Unittest.DefaultImportEnumExtension, ImportEnum.IMPORT_BAZ) - .SetExtension(Unittest.DefaultInt32Extension, 123) - .SetExtension(Unittest.DefaultInt64Extension, 123) - .SetExtension(Unittest.DefaultNestedEnumExtension, TestAllTypes.Types.NestedEnum.FOO) - .SetExtension(Unittest.DefaultSfixed32Extension, 123) - .SetExtension(Unittest.DefaultSfixed64Extension, 123) - .SetExtension(Unittest.DefaultSint32Extension, 123) - .SetExtension(Unittest.DefaultSint64Extension, 123) - .SetExtension(Unittest.DefaultStringExtension, "123") - .SetExtension(Unittest.DefaultStringPieceExtension, "123") - .SetExtension(Unittest.DefaultUint32Extension, 123u) - .SetExtension(Unittest.DefaultUint64Extension, 123u) - //Optional - .SetExtension(Unittest.OptionalBoolExtension, true) - .SetExtension(Unittest.OptionalBytesExtension, ByteString.CopyFromUtf8("123")) - .SetExtension(Unittest.OptionalCordExtension, "123") - .SetExtension(Unittest.OptionalDoubleExtension, 123) - .SetExtension(Unittest.OptionalFixed32Extension, 123u) - .SetExtension(Unittest.OptionalFixed64Extension, 123u) - .SetExtension(Unittest.OptionalFloatExtension, 123) - .SetExtension(Unittest.OptionalForeignEnumExtension, ForeignEnum.FOREIGN_BAZ) - .SetExtension(Unittest.OptionalImportEnumExtension, ImportEnum.IMPORT_BAZ) - .SetExtension(Unittest.OptionalInt32Extension, 123) - .SetExtension(Unittest.OptionalInt64Extension, 123) - .SetExtension(Unittest.OptionalNestedEnumExtension, TestAllTypes.Types.NestedEnum.FOO) - .SetExtension(Unittest.OptionalSfixed32Extension, 123) - .SetExtension(Unittest.OptionalSfixed64Extension, 123) - .SetExtension(Unittest.OptionalSint32Extension, 123) - .SetExtension(Unittest.OptionalSint64Extension, 123) - .SetExtension(Unittest.OptionalStringExtension, "123") - .SetExtension(Unittest.OptionalStringPieceExtension, "123") - .SetExtension(Unittest.OptionalUint32Extension, 123u) - .SetExtension(Unittest.OptionalUint64Extension, 123u) - //Repeated - .AddExtension(Unittest.RepeatedBoolExtension, true) - .AddExtension(Unittest.RepeatedBytesExtension, ByteString.CopyFromUtf8("123")) - .AddExtension(Unittest.RepeatedCordExtension, "123") - .AddExtension(Unittest.RepeatedDoubleExtension, 123) - .AddExtension(Unittest.RepeatedFixed32Extension, 123u) - .AddExtension(Unittest.RepeatedFixed64Extension, 123u) - .AddExtension(Unittest.RepeatedFloatExtension, 123) - .AddExtension(Unittest.RepeatedForeignEnumExtension, ForeignEnum.FOREIGN_BAZ) - .AddExtension(Unittest.RepeatedImportEnumExtension, ImportEnum.IMPORT_BAZ) - .AddExtension(Unittest.RepeatedInt32Extension, 123) - .AddExtension(Unittest.RepeatedInt64Extension, 123) - .AddExtension(Unittest.RepeatedNestedEnumExtension, TestAllTypes.Types.NestedEnum.FOO) - .AddExtension(Unittest.RepeatedSfixed32Extension, 123) - .AddExtension(Unittest.RepeatedSfixed64Extension, 123) - .AddExtension(Unittest.RepeatedSint32Extension, 123) - .AddExtension(Unittest.RepeatedSint64Extension, 123) - .AddExtension(Unittest.RepeatedStringExtension, "123") - .AddExtension(Unittest.RepeatedStringPieceExtension, "123") - .AddExtension(Unittest.RepeatedUint32Extension, 123u) - .AddExtension(Unittest.RepeatedUint64Extension, 123u) - ; - TestAllExtensions msg = builder.Build(); - - ExtensionRegistry registry = ExtensionRegistry.CreateInstance(); - Unittest.RegisterAllExtensions(registry); - - TestAllExtensions.Builder copyBuilder = TestAllExtensions.CreateBuilder().MergeFrom(msg.ToByteArray(), - registry); - TestAllExtensions copy = copyBuilder.Build(); - - Assert.AreEqual(msg.ToByteArray(), copy.ToByteArray()); - - Assert.AreEqual(true, copy.GetExtension(Unittest.DefaultBoolExtension)); - Assert.AreEqual(ByteString.CopyFromUtf8("123"), copy.GetExtension(Unittest.DefaultBytesExtension)); - Assert.AreEqual("123", copy.GetExtension(Unittest.DefaultCordExtension)); - Assert.AreEqual(123, copy.GetExtension(Unittest.DefaultDoubleExtension)); - Assert.AreEqual(123u, copy.GetExtension(Unittest.DefaultFixed32Extension)); - Assert.AreEqual(123u, copy.GetExtension(Unittest.DefaultFixed64Extension)); - Assert.AreEqual(123, copy.GetExtension(Unittest.DefaultFloatExtension)); - Assert.AreEqual(ForeignEnum.FOREIGN_BAZ, copy.GetExtension(Unittest.DefaultForeignEnumExtension)); - Assert.AreEqual(ImportEnum.IMPORT_BAZ, copy.GetExtension(Unittest.DefaultImportEnumExtension)); - Assert.AreEqual(123, copy.GetExtension(Unittest.DefaultInt32Extension)); - Assert.AreEqual(123, copy.GetExtension(Unittest.DefaultInt64Extension)); - Assert.AreEqual(TestAllTypes.Types.NestedEnum.FOO, - copy.GetExtension(Unittest.DefaultNestedEnumExtension)); - Assert.AreEqual(123, copy.GetExtension(Unittest.DefaultSfixed32Extension)); - Assert.AreEqual(123, copy.GetExtension(Unittest.DefaultSfixed64Extension)); - Assert.AreEqual(123, copy.GetExtension(Unittest.DefaultSint32Extension)); - Assert.AreEqual(123, copy.GetExtension(Unittest.DefaultSint64Extension)); - Assert.AreEqual("123", copy.GetExtension(Unittest.DefaultStringExtension)); - Assert.AreEqual("123", copy.GetExtension(Unittest.DefaultStringPieceExtension)); - Assert.AreEqual(123u, copy.GetExtension(Unittest.DefaultUint32Extension)); - Assert.AreEqual(123u, copy.GetExtension(Unittest.DefaultUint64Extension)); - - Assert.AreEqual(true, copy.GetExtension(Unittest.OptionalBoolExtension)); - Assert.AreEqual(ByteString.CopyFromUtf8("123"), copy.GetExtension(Unittest.OptionalBytesExtension)); - Assert.AreEqual("123", copy.GetExtension(Unittest.OptionalCordExtension)); - Assert.AreEqual(123, copy.GetExtension(Unittest.OptionalDoubleExtension)); - Assert.AreEqual(123u, copy.GetExtension(Unittest.OptionalFixed32Extension)); - Assert.AreEqual(123u, copy.GetExtension(Unittest.OptionalFixed64Extension)); - Assert.AreEqual(123, copy.GetExtension(Unittest.OptionalFloatExtension)); - Assert.AreEqual(ForeignEnum.FOREIGN_BAZ, copy.GetExtension(Unittest.OptionalForeignEnumExtension)); - Assert.AreEqual(ImportEnum.IMPORT_BAZ, copy.GetExtension(Unittest.OptionalImportEnumExtension)); - Assert.AreEqual(123, copy.GetExtension(Unittest.OptionalInt32Extension)); - Assert.AreEqual(123, copy.GetExtension(Unittest.OptionalInt64Extension)); - Assert.AreEqual(TestAllTypes.Types.NestedEnum.FOO, - copy.GetExtension(Unittest.OptionalNestedEnumExtension)); - Assert.AreEqual(123, copy.GetExtension(Unittest.OptionalSfixed32Extension)); - Assert.AreEqual(123, copy.GetExtension(Unittest.OptionalSfixed64Extension)); - Assert.AreEqual(123, copy.GetExtension(Unittest.OptionalSint32Extension)); - Assert.AreEqual(123, copy.GetExtension(Unittest.OptionalSint64Extension)); - Assert.AreEqual("123", copy.GetExtension(Unittest.OptionalStringExtension)); - Assert.AreEqual("123", copy.GetExtension(Unittest.OptionalStringPieceExtension)); - Assert.AreEqual(123u, copy.GetExtension(Unittest.OptionalUint32Extension)); - Assert.AreEqual(123u, copy.GetExtension(Unittest.OptionalUint64Extension)); - - Assert.AreEqual(true, copy.GetExtension(Unittest.RepeatedBoolExtension, 0)); - Assert.AreEqual(ByteString.CopyFromUtf8("123"), - copy.GetExtension(Unittest.RepeatedBytesExtension, 0)); - Assert.AreEqual("123", copy.GetExtension(Unittest.RepeatedCordExtension, 0)); - Assert.AreEqual(123, copy.GetExtension(Unittest.RepeatedDoubleExtension, 0)); - Assert.AreEqual(123u, copy.GetExtension(Unittest.RepeatedFixed32Extension, 0)); - Assert.AreEqual(123u, copy.GetExtension(Unittest.RepeatedFixed64Extension, 0)); - Assert.AreEqual(123, copy.GetExtension(Unittest.RepeatedFloatExtension, 0)); - Assert.AreEqual(ForeignEnum.FOREIGN_BAZ, - copy.GetExtension(Unittest.RepeatedForeignEnumExtension, 0)); - Assert.AreEqual(ImportEnum.IMPORT_BAZ, copy.GetExtension(Unittest.RepeatedImportEnumExtension, 0)); - Assert.AreEqual(123, copy.GetExtension(Unittest.RepeatedInt32Extension, 0)); - Assert.AreEqual(123, copy.GetExtension(Unittest.RepeatedInt64Extension, 0)); - Assert.AreEqual(TestAllTypes.Types.NestedEnum.FOO, - copy.GetExtension(Unittest.RepeatedNestedEnumExtension, 0)); - Assert.AreEqual(123, copy.GetExtension(Unittest.RepeatedSfixed32Extension, 0)); - Assert.AreEqual(123, copy.GetExtension(Unittest.RepeatedSfixed64Extension, 0)); - Assert.AreEqual(123, copy.GetExtension(Unittest.RepeatedSint32Extension, 0)); - Assert.AreEqual(123, copy.GetExtension(Unittest.RepeatedSint64Extension, 0)); - Assert.AreEqual("123", copy.GetExtension(Unittest.RepeatedStringExtension, 0)); - Assert.AreEqual("123", copy.GetExtension(Unittest.RepeatedStringPieceExtension, 0)); - Assert.AreEqual(123u, copy.GetExtension(Unittest.RepeatedUint32Extension, 0)); - Assert.AreEqual(123u, copy.GetExtension(Unittest.RepeatedUint64Extension, 0)); - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers.Test/FieldPresenceTest.cs b/csharp/src/ProtocolBuffers.Test/FieldPresenceTest.cs deleted file mode 100644 index 66214221..00000000 --- a/csharp/src/ProtocolBuffers.Test/FieldPresenceTest.cs +++ /dev/null @@ -1,198 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2015 Google Inc. All rights reserved. -// Author: jieluo@google.com (Jie Luo) -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using Google.ProtocolBuffers.Descriptors; -using Google.ProtocolBuffers.TestProtos.Proto3; -using NUnit.Framework; - -namespace Google.ProtocolBuffers -{ - public class FieldPresenceTest - { - private void CheckHasMethodRemoved(Type proto2Type, Type proto3Type, string name) - { - Assert.NotNull(proto2Type.GetProperty(name)); - Assert.NotNull(proto2Type.GetProperty("Has" + name)); - Assert.NotNull(proto3Type.GetProperty(name)); - Assert.Null(proto3Type.GetProperty("Has" + name)); - } - - [Test] - public void TestHasMethod() - { - // Optional non-message fields don't have HasFoo method generated - Type proto2Type = typeof(Google.ProtocolBuffers.TestProtos.TestAllTypes); - Type proto3Type = typeof(TestAllTypes); - CheckHasMethodRemoved(proto2Type, proto3Type, "OptionalInt32"); - CheckHasMethodRemoved(proto2Type, proto3Type, "OptionalString"); - CheckHasMethodRemoved(proto2Type, proto3Type, "OptionalBytes"); - CheckHasMethodRemoved(proto2Type, proto3Type, "OptionalNestedEnum"); - - Type proto2BuilderType = typeof(Google.ProtocolBuffers.TestProtos.TestAllTypes.Builder); - Type proto3BuilderType = typeof(TestAllTypes.Builder); - CheckHasMethodRemoved(proto2BuilderType, proto3BuilderType, "OptionalInt32"); - CheckHasMethodRemoved(proto2BuilderType, proto3BuilderType, "OptionalString"); - CheckHasMethodRemoved(proto2BuilderType, proto3BuilderType, "OptionalBytes"); - CheckHasMethodRemoved(proto2BuilderType, proto3BuilderType, "OptionalNestedEnum"); - - // message fields still have the HasFoo method generated - Assert.IsFalse(TestAllTypes.CreateBuilder().Build().HasOptionalNestedMessage); - Assert.IsFalse(TestAllTypes.CreateBuilder().HasOptionalNestedMessage); - - // oneof fields don't have the HasFoo method (even for message types) - CheckHasMethodRemoved(proto2Type, proto3Type, "OneofUint32"); - CheckHasMethodRemoved(proto2Type, proto3Type, "OneofString"); - CheckHasMethodRemoved(proto2Type, proto3Type, "OneofNestedMessage"); - - CheckHasMethodRemoved(proto2BuilderType, proto3BuilderType, "OneofUint32"); - CheckHasMethodRemoved(proto2BuilderType, proto3BuilderType, "OneofString"); - CheckHasMethodRemoved(proto2BuilderType, proto3BuilderType, "OneofNestedMessage"); - } - - [Test] - public void TestFieldPresence() - { - // Optional non-message fields set to their default value are treated the same - // way as not set. - - // Serialization will ignore such fields. - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - builder.SetOptionalInt32(0); - builder.SetOptionalString(""); - builder.SetOptionalBytes(ByteString.Empty); - builder.SetOptionalNestedEnum(TestAllTypes.Types.NestedEnum.FOO); - TestAllTypes message = builder.Build(); - Assert.AreEqual(0, message.SerializedSize); - - // Test merge - TestAllTypes.Builder a = TestAllTypes.CreateBuilder(); - a.SetOptionalInt32(1); - a.SetOptionalString("x"); - a.SetOptionalBytes(ByteString.CopyFromUtf8("y")); - a.SetOptionalNestedEnum(TestAllTypes.Types.NestedEnum.BAR); - a.MergeFrom(message); - TestAllTypes messageA = a.Build(); - Assert.AreEqual(1, messageA.OptionalInt32); - Assert.AreEqual("x", messageA.OptionalString); - Assert.AreEqual(ByteString.CopyFromUtf8("y"), messageA.OptionalBytes); - Assert.AreEqual(TestAllTypes.Types.NestedEnum.BAR, messageA.OptionalNestedEnum); - - // equals/hashCode should produce the same results - TestAllTypes empty = TestAllTypes.CreateBuilder().Build(); - Assert.IsTrue(empty.Equals(message)); - Assert.IsTrue(message.Equals(empty)); - Assert.AreEqual(empty.GetHashCode(), message.GetHashCode()); - } - - [Test] - public void TestFieldPresenceReflection() - { - MessageDescriptor descriptor = TestAllTypes.Descriptor; - FieldDescriptor optionalInt32Field = descriptor.FindFieldByName("optional_int32"); - FieldDescriptor optionalStringField = descriptor.FindFieldByName("optional_string"); - FieldDescriptor optionalBytesField = descriptor.FindFieldByName("optional_bytes"); - FieldDescriptor optionalNestedEnumField = descriptor.FindFieldByName("optional_nested_enum"); - FieldDescriptor oneofUint32Field = descriptor.FindFieldByName("oneof_uint32"); - - TestAllTypes message = TestAllTypes.CreateBuilder().Build(); - Assert.IsFalse(message.HasField(optionalInt32Field)); - Assert.IsFalse(message.HasField(optionalStringField)); - Assert.IsFalse(message.HasField(optionalBytesField)); - Assert.IsFalse(message.HasField(optionalNestedEnumField)); - - // Set to default value is seen as not present for optional fields. - // Set to default value is seen as present for oneof fields. - message = TestAllTypes.CreateBuilder() - .SetOptionalInt32(0) - .SetOptionalString("") - .SetOptionalBytes(ByteString.Empty) - .SetOptionalNestedEnum(TestAllTypes.Types.NestedEnum.FOO) - .SetOneofUint32(0U) - .Build(); - Assert.IsFalse(message.HasField(optionalInt32Field)); - Assert.IsFalse(message.HasField(optionalStringField)); - Assert.IsFalse(message.HasField(optionalBytesField)); - Assert.IsFalse(message.HasField(optionalNestedEnumField)); - Assert.IsTrue(message.HasField(oneofUint32Field)); - Assert.AreEqual(1, message.AllFields.Count); - - // Set to non-defalut value is seen as present - message = TestAllTypes.CreateBuilder() - .SetOptionalInt32(1) - .SetOptionalString("x") - .SetOptionalBytes(ByteString.CopyFromUtf8("y")) - .SetOptionalNestedEnum(TestAllTypes.Types.NestedEnum.BAR) - .Build(); - Assert.IsTrue(message.HasField(optionalInt32Field)); - Assert.IsTrue(message.HasField(optionalStringField)); - Assert.IsTrue(message.HasField(optionalBytesField)); - Assert.IsTrue(message.HasField(optionalNestedEnumField)); - Assert.AreEqual(4, message.AllFields.Count); - } - - [Test] - public void TestMessageField() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - Assert.IsFalse(builder.HasOptionalNestedMessage); - Assert.IsFalse(builder.Build().HasOptionalNestedMessage); - - // Unlike non-message fields, if we set default value to message field, the field - // shoule be seem as present. - builder.SetOptionalNestedMessage(TestAllTypes.Types.NestedMessage.DefaultInstance); - Assert.IsTrue(builder.HasOptionalNestedMessage); - Assert.IsTrue(builder.Build().HasOptionalNestedMessage); - } - - [Test] - public void TestSerializeAndParse() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - builder.SetOptionalInt32(1234); - builder.SetOptionalString("hello"); - builder.SetOptionalNestedMessage(TestAllTypes.Types.NestedMessage.DefaultInstance); - builder.SetOneofUint32(0U); - ByteString data = builder.Build().ToByteString(); - - TestAllTypes message = TestAllTypes.ParseFrom(data); - Assert.AreEqual(1234, message.OptionalInt32); - Assert.AreEqual("hello", message.OptionalString); - Assert.AreEqual(ByteString.Empty, message.OptionalBytes); - Assert.AreEqual(TestAllTypes.Types.NestedEnum.FOO, message.OptionalNestedEnum); - Assert.IsTrue(message.HasOptionalNestedMessage); - Assert.AreEqual(0, message.OptionalNestedMessage.Bb); - Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.OneofUint32, message.OneofFieldCase); - } - } -} diff --git a/csharp/src/ProtocolBuffers.Test/GeneratedBuilderTest.cs b/csharp/src/ProtocolBuffers.Test/GeneratedBuilderTest.cs deleted file mode 100644 index 257f5001..00000000 --- a/csharp/src/ProtocolBuffers.Test/GeneratedBuilderTest.cs +++ /dev/null @@ -1,102 +0,0 @@ -using System; -using System.Collections.Generic; -using Google.ProtocolBuffers.TestProtos; -using NUnit.Framework; - -namespace Google.ProtocolBuffers -{ - public class GeneratedBuilderTest - { - class OneTimeEnumerator : IEnumerable - { - readonly T _item; - bool _enumerated; - public OneTimeEnumerator(T item) - { - _item = item; - } - public IEnumerator GetEnumerator() - { - Assert.IsFalse(_enumerated); - _enumerated = true; - yield return _item; - } - System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - } - - [Test] - public void DoesNotEnumerateTwiceForMessageList() - { - TestAllTypes.Builder b = new TestAllTypes.Builder(); - b.AddRangeRepeatedForeignMessage(new OneTimeEnumerator(ForeignMessage.DefaultInstance)); - } - - [Test] - public void DoesNotEnumerateTwiceForPrimitiveList() - { - TestAllTypes.Builder b = new TestAllTypes.Builder(); - b.AddRangeRepeatedInt32(new OneTimeEnumerator(1)); - } - - [Test] - public void DoesNotEnumerateTwiceForStringList() - { - TestAllTypes.Builder b = new TestAllTypes.Builder(); - b.AddRangeRepeatedString(new OneTimeEnumerator("test")); - } - - [Test] - public void DoesNotEnumerateTwiceForEnumList() - { - TestAllTypes.Builder b = new TestAllTypes.Builder(); - b.AddRangeRepeatedForeignEnum(new OneTimeEnumerator(ForeignEnum.FOREIGN_BAR)); - } - - [Test] - public void DoesNotAddNullToMessageListByAddRange() - { - TestAllTypes.Builder b = new TestAllTypes.Builder(); - Assert.Throws(() => b.AddRangeRepeatedForeignMessage(new ForeignMessage[] { null })); - } - - [Test] - public void DoesNotAddNullToMessageListByAdd() - { - TestAllTypes.Builder b = new TestAllTypes.Builder(); - Assert.Throws(() => b.AddRepeatedForeignMessage((ForeignMessage)null)); - } - - [Test] - public void DoesNotAddNullToMessageListBySet() - { - TestAllTypes.Builder b = new TestAllTypes.Builder(); - b.AddRepeatedForeignMessage(ForeignMessage.DefaultInstance); - Assert.Throws(() => b.SetRepeatedForeignMessage(0, (ForeignMessage)null)); - } - - [Test] - public void DoesNotAddNullToStringListByAddRange() - { - TestAllTypes.Builder b = new TestAllTypes.Builder(); - Assert.Throws(() => b.AddRangeRepeatedString(new String[] { null })); - } - - [Test] - public void DoesNotAddNullToStringListByAdd() - { - TestAllTypes.Builder b = new TestAllTypes.Builder(); - Assert.Throws(() => b.AddRepeatedString(null)); - } - - [Test] - public void DoesNotAddNullToStringListBySet() - { - TestAllTypes.Builder b = new TestAllTypes.Builder(); - b.AddRepeatedString("one"); - Assert.Throws(() => b.SetRepeatedString(0, null)); - } - } -} diff --git a/csharp/src/ProtocolBuffers.Test/GeneratedMessageTest.cs b/csharp/src/ProtocolBuffers.Test/GeneratedMessageTest.cs index 4f669449..c5564060 100644 --- a/csharp/src/ProtocolBuffers.Test/GeneratedMessageTest.cs +++ b/csharp/src/ProtocolBuffers.Test/GeneratedMessageTest.cs @@ -1,776 +1,153 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; +using System; using System.Collections.Generic; -using Google.ProtocolBuffers.Descriptors; -using Google.ProtocolBuffers.Collections; -using Google.ProtocolBuffers.TestProtos; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Google.Protobuf.TestProtos; using NUnit.Framework; -namespace Google.ProtocolBuffers +namespace Google.Protobuf { + /// + /// Tests around the generated TestAllTypes message. + /// public class GeneratedMessageTest { - private readonly ReflectionTester reflectionTester; - private readonly ReflectionTester extensionsReflectionTester; - - public GeneratedMessageTest() - { - reflectionTester = ReflectionTester.CreateTestAllTypesInstance(); - extensionsReflectionTester = ReflectionTester.CreateTestAllExtensionsInstance(); - } - - [Test] - public void RepeatedAddPrimitiveBeforeBuild() - { - TestAllTypes message = new TestAllTypes.Builder {RepeatedInt32List = {1, 2, 3}}.Build(); - TestUtil.AssertEqual(new int[] {1, 2, 3}, message.RepeatedInt32List); - } - - [Test] - public void AddPrimitiveFailsAfterBuild() - { - TestAllTypes.Builder builder = new TestAllTypes.Builder(); - IList list = builder.RepeatedInt32List; - list.Add(1); // Fine - builder.Build(); - - Assert.Throws(() => list.Add(2)); - } - - [Test] - public void RepeatedAddMessageBeforeBuild() - { - TestAllTypes message = new TestAllTypes.Builder - { - RepeatedNestedMessageList = - {new TestAllTypes.Types.NestedMessage.Builder {Bb = 10}.Build()} - }.Build(); - Assert.AreEqual(1, message.RepeatedNestedMessageCount); - Assert.AreEqual(10, message.RepeatedNestedMessageList[0].Bb); - } - - [Test] - public void AddMessageFailsAfterBuild() - { - TestAllTypes.Builder builder = new TestAllTypes.Builder(); - IList list = builder.RepeatedNestedMessageList; - builder.Build(); - - Assert.Throws(() => list.Add(new TestAllTypes.Types.NestedMessage.Builder { Bb = 10 }.Build())); - } - - [Test] - public void DefaultInstance() - { - Assert.AreSame(TestAllTypes.DefaultInstance, TestAllTypes.DefaultInstance.DefaultInstanceForType); - Assert.AreSame(TestAllTypes.DefaultInstance, TestAllTypes.CreateBuilder().DefaultInstanceForType); - } - - [Test] - public void Accessors() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - TestUtil.SetAllFields(builder); - TestAllTypes message = builder.Build(); - TestUtil.AssertAllFieldsSet(message); - } - - [Test] - public void SettersRejectNull() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - Assert.Throws(() => builder.SetOptionalString(null)); - Assert.Throws(() => builder.SetOptionalBytes(null)); - Assert.Throws( - () => builder.SetOptionalNestedMessage((TestAllTypes.Types.NestedMessage) null)); - Assert.Throws( - () => builder.SetOptionalNestedMessage((TestAllTypes.Types.NestedMessage.Builder) null)); - Assert.Throws(() => builder.AddRepeatedString(null)); - Assert.Throws(() => builder.AddRepeatedBytes(null)); - Assert.Throws( - () => builder.AddRepeatedNestedMessage((TestAllTypes.Types.NestedMessage) null)); - Assert.Throws( - () => builder.AddRepeatedNestedMessage((TestAllTypes.Types.NestedMessage.Builder) null)); - } - - [Test] - public void RepeatedSetters() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - TestUtil.SetAllFields(builder); - TestUtil.ModifyRepeatedFields(builder); - TestAllTypes message = builder.Build(); - TestUtil.AssertRepeatedFieldsModified(message); - } - - [Test] - public void RepeatedAppend() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - - builder.AddRangeRepeatedInt32(new int[] {1, 2, 3, 4}); - builder.AddRangeRepeatedForeignEnum((new ForeignEnum[] {ForeignEnum.FOREIGN_BAZ})); - - ForeignMessage foreignMessage = ForeignMessage.CreateBuilder().SetC(12).Build(); - builder.AddRangeRepeatedForeignMessage(new ForeignMessage[] {foreignMessage}); - - TestAllTypes message = builder.Build(); - TestUtil.AssertEqual(message.RepeatedInt32List, new int[] {1, 2, 3, 4}); - TestUtil.AssertEqual(message.RepeatedForeignEnumList, new ForeignEnum[] {ForeignEnum.FOREIGN_BAZ}); - Assert.AreEqual(1, message.RepeatedForeignMessageCount); - Assert.AreEqual(12, message.GetRepeatedForeignMessage(0).C); - } - - [Test] - public void RepeatedAppendRejectsNull() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - - ForeignMessage foreignMessage = ForeignMessage.CreateBuilder().SetC(12).Build(); - Assert.Throws( - () => builder.AddRangeRepeatedForeignMessage(new[] {foreignMessage, null})); - Assert.Throws(() => builder.AddRangeRepeatedForeignMessage(null)); - Assert.Throws(() => builder.AddRangeRepeatedForeignEnum(null)); - Assert.Throws(() => builder.AddRangeRepeatedString(new[] {"one", null})); - Assert.Throws( - () => builder.AddRangeRepeatedBytes(new[] {TestUtil.ToBytes("one"), null})); - } - - [Test] - public void SettingForeignMessageUsingBuilder() - { - TestAllTypes message = TestAllTypes.CreateBuilder() - // Pass builder for foreign message instance. - .SetOptionalForeignMessage(ForeignMessage.CreateBuilder().SetC(123)) - .Build(); - TestAllTypes expectedMessage = TestAllTypes.CreateBuilder() - // Create expected version passing foreign message instance explicitly. - .SetOptionalForeignMessage(ForeignMessage.CreateBuilder().SetC(123).Build()) - .Build(); - Assert.AreEqual(expectedMessage, message); - } - - [Test] - public void SettingRepeatedForeignMessageUsingBuilder() - { - TestAllTypes message = TestAllTypes.CreateBuilder() - // Pass builder for foreign message instance. - .AddRepeatedForeignMessage(ForeignMessage.CreateBuilder().SetC(456)) - .Build(); - TestAllTypes expectedMessage = TestAllTypes.CreateBuilder() - // Create expected version passing foreign message instance explicitly. - .AddRepeatedForeignMessage(ForeignMessage.CreateBuilder().SetC(456).Build()) - .Build(); - Assert.AreEqual(expectedMessage, message); - } - - [Test] - public void SettingRepeatedValuesUsingRangeInCollectionInitializer() - { - int[] values = {1, 2, 3}; - TestAllTypes message = new TestAllTypes.Builder - { - RepeatedSint32List = {values} - }.Build(); - Assert.IsTrue(Lists.Equals(values, message.RepeatedSint32List)); - } - - [Test] - public void SettingRepeatedValuesUsingIndividualValuesInCollectionInitializer() - { - TestAllTypes message = new TestAllTypes.Builder - { - RepeatedSint32List = {6, 7} - }.Build(); - Assert.IsTrue(Lists.Equals(new int[] {6, 7}, message.RepeatedSint32List)); - } - - [Test] - public void Defaults() - { - TestUtil.AssertClear(TestAllTypes.DefaultInstance); - TestUtil.AssertClear(TestAllTypes.CreateBuilder().Build()); - - Assert.AreEqual("\u1234", TestExtremeDefaultValues.DefaultInstance.Utf8String); - } - - [Test] - public void ReflectionGetters() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - TestUtil.SetAllFields(builder); - TestAllTypes message = builder.Build(); - reflectionTester.AssertAllFieldsSetViaReflection(message); - } - - [Test] - public void ReflectionSetters() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - reflectionTester.SetAllFieldsViaReflection(builder); - TestAllTypes message = builder.Build(); - TestUtil.AssertAllFieldsSet(message); - } - - [Test] - public void ReflectionClear() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - reflectionTester.SetAllFieldsViaReflection(builder); - reflectionTester.ClearAllFieldsViaReflection(builder); - TestAllTypes message = builder.Build(); - TestUtil.AssertClear(message); - } - - [Test] - public void ReflectionSettersRejectNull() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - reflectionTester.AssertReflectionSettersRejectNull(builder); - } - - [Test] - public void ReflectionRepeatedSetters() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - reflectionTester.SetAllFieldsViaReflection(builder); - reflectionTester.ModifyRepeatedFieldsViaReflection(builder); - TestAllTypes message = builder.Build(); - TestUtil.AssertRepeatedFieldsModified(message); - } - - [Test] - public void TestReflectionRepeatedSettersRejectNull() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - reflectionTester.AssertReflectionRepeatedSettersRejectNull(builder); - } - - [Test] - public void ReflectionDefaults() - { - TestUtil.TestInMultipleCultures(() => - { - reflectionTester.AssertClearViaReflection( - TestAllTypes.DefaultInstance); - reflectionTester.AssertClearViaReflection( - TestAllTypes.CreateBuilder().Build()); - }); - } - - [Test] - public void ReflectionGetOneof() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - reflectionTester.SetAllFieldsViaReflection(builder); - Descriptors.OneofDescriptor oneof = TestAllTypes.Descriptor.Oneofs[0]; - Descriptors.FieldDescriptor field = TestAllTypes.Descriptor.FindFieldByName("oneof_bytes"); - Assert.AreSame(field, builder.OneofFieldDescriptor(oneof)); - } - - [Test] - public void ReflectionClearOneof() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - reflectionTester.SetAllFieldsViaReflection(builder); - OneofDescriptor oneof = TestAllTypes.Descriptor.Oneofs[0]; - FieldDescriptor field = TestAllTypes.Descriptor.FindFieldByName("oneof_bytes"); - - Assert.IsTrue(builder.HasOneof(oneof)); - Assert.IsTrue(builder.HasField(field)); - builder.ClearOneof(oneof); - Assert.IsFalse(builder.HasOneof(oneof)); - Assert.IsFalse(builder.HasField(field)); - } - - // ================================================================= - // Extensions. - - [Test] - public void ExtensionAccessors() - { - TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder(); - TestUtil.SetAllExtensions(builder); - TestAllExtensions message = builder.Build(); - TestUtil.AssertAllExtensionsSet(message); - } - - [Test] - public void ExtensionRepeatedSetters() - { - TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder(); - TestUtil.SetAllExtensions(builder); - TestUtil.ModifyRepeatedExtensions(builder); - TestAllExtensions message = builder.Build(); - TestUtil.AssertRepeatedExtensionsModified(message); - } - - [Test] - public void ExtensionDefaults() - { - TestUtil.AssertExtensionsClear(TestAllExtensions.DefaultInstance); - TestUtil.AssertExtensionsClear(TestAllExtensions.CreateBuilder().Build()); - } - - [Test] - public void ExtensionReflectionGetters() - { - TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder(); - TestUtil.SetAllExtensions(builder); - TestAllExtensions message = builder.Build(); - extensionsReflectionTester.AssertAllFieldsSetViaReflection(message); - } - - [Test] - public void ExtensionReflectionSetters() - { - TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder(); - extensionsReflectionTester.SetAllFieldsViaReflection(builder); - TestAllExtensions message = builder.Build(); - TestUtil.AssertAllExtensionsSet(message); - } - [Test] - public void ExtensionReflectionSettersRejectNull() - { - TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder(); - extensionsReflectionTester.AssertReflectionSettersRejectNull(builder); - } - - [Test] - public void ExtensionReflectionRepeatedSetters() - { - TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder(); - extensionsReflectionTester.SetAllFieldsViaReflection(builder); - extensionsReflectionTester.ModifyRepeatedFieldsViaReflection(builder); - TestAllExtensions message = builder.Build(); - TestUtil.AssertRepeatedExtensionsModified(message); - } - - [Test] - public void ExtensionReflectionRepeatedSettersRejectNull() - { - TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder(); - extensionsReflectionTester.AssertReflectionRepeatedSettersRejectNull(builder); - } - - [Test] - public void ExtensionReflectionDefaults() - { - TestUtil.TestInMultipleCultures(() => - { - extensionsReflectionTester.AssertClearViaReflection( - TestAllExtensions.DefaultInstance); - extensionsReflectionTester.AssertClearViaReflection( - TestAllExtensions.CreateBuilder().Build()); - }); - } - - [Test] - public void ClearExtension() - { - // ClearExtension() is not actually used in TestUtil, so try it manually. - Assert.IsFalse(TestAllExtensions.CreateBuilder() - .SetExtension(Unittest.OptionalInt32Extension, 1) - .ClearExtension(Unittest.OptionalInt32Extension) - .HasExtension(Unittest.OptionalInt32Extension)); - Assert.AreEqual(0, TestAllExtensions.CreateBuilder() - .AddExtension(Unittest.RepeatedInt32Extension, 1) - .ClearExtension(Unittest.RepeatedInt32Extension) - .GetExtensionCount(Unittest.RepeatedInt32Extension)); - } - - [Test] - public void ExtensionMergeFrom() - { - TestAllExtensions original = TestAllExtensions.CreateBuilder() - .SetExtension(Unittest.OptionalInt32Extension, 1).Build(); - TestAllExtensions merged = - TestAllExtensions.CreateBuilder().MergeFrom(original).Build(); - Assert.IsTrue((merged.HasExtension(Unittest.OptionalInt32Extension))); - Assert.AreEqual(1, (int) merged.GetExtension(Unittest.OptionalInt32Extension)); - } - - /* Removed multiple files option for the moment - [Test] - public void MultipleFilesOption() { - // We mostly just want to check that things compile. - MessageWithNoOuter message = MessageWithNoOuter.CreateBuilder() - .SetNested(MessageWithNoOuter.Types.NestedMessage.CreateBuilder().SetI(1)) - .AddForeign(TestAllTypes.CreateBuilder().SetOptionalInt32(1)) - .SetNestedEnum(MessageWithNoOuter.Types.NestedEnum.BAZ) - .SetForeignEnum(EnumWithNoOuter.BAR) - .Build(); - Assert.AreEqual(message, MessageWithNoOuter.ParseFrom(message.ToByteString())); - - Assert.AreEqual(MultiFileProto.DescriptorProtoFile, MessageWithNoOuter.DescriptorProtoFile.File); - - FieldDescriptor field = MessageWithNoOuter.DescriptorProtoFile.FindDescriptor("foreign_enum"); - Assert.AreEqual(MultiFileProto.DescriptorProtoFile.FindTypeByName("EnumWithNoOuter") - .FindValueByNumber((int)EnumWithNoOuter.BAR), message[field]); - - Assert.AreEqual(MultiFileProto.DescriptorProtoFile, ServiceWithNoOuter.DescriptorProtoFile.File); - - Assert.IsFalse(TestAllExtensions.DefaultInstance.HasExtension(MultiFileProto.ExtensionWithOuter)); - }*/ - - [Test] - public void OptionalFieldWithRequiredSubfieldsOptimizedForSize() - { - TestOptionalOptimizedForSize message = TestOptionalOptimizedForSize.DefaultInstance; - Assert.IsTrue(message.IsInitialized); - - message = TestOptionalOptimizedForSize.CreateBuilder().SetO( - TestRequiredOptimizedForSize.CreateBuilder().BuildPartial() - ).BuildPartial(); - Assert.IsFalse(message.IsInitialized); - - message = TestOptionalOptimizedForSize.CreateBuilder().SetO( - TestRequiredOptimizedForSize.CreateBuilder().SetX(5).BuildPartial() - ).BuildPartial(); - Assert.IsTrue(message.IsInitialized); - } - - [Test] - public void OptimizedForSizeMergeUsesAllFieldsFromTarget() - { - TestOptimizedForSize withFieldSet = new TestOptimizedForSize.Builder {I = 10}.Build(); - TestOptimizedForSize.Builder builder = new TestOptimizedForSize.Builder(); - builder.MergeFrom(withFieldSet); - TestOptimizedForSize built = builder.Build(); - Assert.AreEqual(10, built.I); - } - - [Test] - public void UninitializedExtensionInOptimizedForSizeMakesMessageUninitialized() - { - TestOptimizedForSize.Builder builder = new TestOptimizedForSize.Builder(); - builder.SetExtension(TestOptimizedForSize.TestExtension2, - new TestRequiredOptimizedForSize.Builder().BuildPartial()); - Assert.IsFalse(builder.IsInitialized); - Assert.IsFalse(builder.BuildPartial().IsInitialized); - - builder = new TestOptimizedForSize.Builder(); - builder.SetExtension(TestOptimizedForSize.TestExtension2, - new TestRequiredOptimizedForSize.Builder {X = 10}.BuildPartial()); - Assert.IsTrue(builder.IsInitialized); - Assert.IsTrue(builder.BuildPartial().IsInitialized); - } - - [Test] - public void ToBuilder() - { - TestAllTypes.Builder builder = TestAllTypes.CreateBuilder(); - TestUtil.SetAllFields(builder); - TestAllTypes message = builder.Build(); - TestUtil.AssertAllFieldsSet(message.ToBuilder().Build()); - } - - [Test] - public void FieldConstantValues() - { - Assert.AreEqual(TestAllTypes.Types.NestedMessage.BbFieldNumber, 1); - Assert.AreEqual(TestAllTypes.OptionalInt32FieldNumber, 1); - Assert.AreEqual(TestAllTypes.OptionalGroupFieldNumber, 16); - Assert.AreEqual(TestAllTypes.OptionalNestedMessageFieldNumber, 18); - Assert.AreEqual(TestAllTypes.OptionalNestedEnumFieldNumber, 21); - Assert.AreEqual(TestAllTypes.RepeatedInt32FieldNumber, 31); - Assert.AreEqual(TestAllTypes.RepeatedGroupFieldNumber, 46); - Assert.AreEqual(TestAllTypes.RepeatedNestedMessageFieldNumber, 48); - Assert.AreEqual(TestAllTypes.RepeatedNestedEnumFieldNumber, 51); - } - - [Test] - public void ExtensionConstantValues() - { - Assert.AreEqual(TestRequired.SingleFieldNumber, 1000); - Assert.AreEqual(TestRequired.MultiFieldNumber, 1001); - Assert.AreEqual(Unittest.OptionalInt32ExtensionFieldNumber, 1); - Assert.AreEqual(Unittest.OptionalGroupExtensionFieldNumber, 16); - Assert.AreEqual(Unittest.OptionalNestedMessageExtensionFieldNumber, 18); - Assert.AreEqual(Unittest.OptionalNestedEnumExtensionFieldNumber, 21); - Assert.AreEqual(Unittest.RepeatedInt32ExtensionFieldNumber, 31); - Assert.AreEqual(Unittest.RepeatedGroupExtensionFieldNumber, 46); - Assert.AreEqual(Unittest.RepeatedNestedMessageExtensionFieldNumber, 48); - Assert.AreEqual(Unittest.RepeatedNestedEnumExtensionFieldNumber, 51); - } - - [Test] - public void EmptyPackedValue() - { - TestPackedTypes empty = new TestPackedTypes.Builder().Build(); - Assert.AreEqual(0, empty.SerializedSize); - } - - // oneof tests - [Test] - public void TestOneofEnumCase() - { - TestOneof2 message = TestOneof2.CreateBuilder() - .SetFooInt(123).SetFooString("foo").SetFooCord("bar").Build(); - TestUtil.AssertAtMostOneFieldSetOneof(message); - } - - [Test] - public void TestClearOneof() - { - TestOneof2.Builder builder = TestOneof2.CreateBuilder().SetFooInt(123); - Assert.AreEqual(TestOneof2.FooOneofCase.FooInt, builder.FooCase); - builder.ClearFoo(); - Assert.AreEqual(TestOneof2.FooOneofCase.None, builder.FooCase); - } - - [Test] - public void TestSetOneofClearsOthers() - { - TestOneof2.Builder builder = TestOneof2.CreateBuilder(); - TestOneof2 message = - builder.SetFooInt(123).SetFooString("foo").Build(); - Assert.IsTrue(message.HasFooString); - TestUtil.AssertAtMostOneFieldSetOneof(message); - - message = builder.SetFooCord("bar").Build(); - Assert.IsTrue(message.HasFooCord); - TestUtil.AssertAtMostOneFieldSetOneof(message); - - message = builder.SetFooStringPiece("baz").Build(); - Assert.IsTrue(message.HasFooStringPiece); - TestUtil.AssertAtMostOneFieldSetOneof(message); - - message = builder.SetFooBytes(TestUtil.ToBytes("qux")).Build(); - Assert.IsTrue(message.HasFooBytes); - TestUtil.AssertAtMostOneFieldSetOneof(message); - - message = builder.SetFooEnum(TestOneof2.Types.NestedEnum.FOO).Build(); - Assert.IsTrue(message.HasFooEnum); - TestUtil.AssertAtMostOneFieldSetOneof(message); - - message = builder.SetFooMessage( - TestOneof2.Types.NestedMessage.CreateBuilder().SetQuxInt(234).Build()).Build(); - Assert.IsTrue(message.HasFooMessage); - TestUtil.AssertAtMostOneFieldSetOneof(message); - - message = builder.SetFooInt(123).Build(); - Assert.IsTrue(message.HasFooInt); - TestUtil.AssertAtMostOneFieldSetOneof(message); - } - - [Test] - public void TestOneofTypes_Primitive() - { - TestOneof2.Builder builder = TestOneof2.CreateBuilder(); - Assert.AreEqual(builder.FooInt, 0); - Assert.IsFalse(builder.HasFooInt); - Assert.IsTrue(builder.SetFooInt(123).HasFooInt); - Assert.AreEqual(builder.FooInt, 123); - TestOneof2 message = builder.BuildPartial(); - Assert.IsTrue(message.HasFooInt); - Assert.AreEqual(message.FooInt, 123); - - Assert.IsFalse(builder.ClearFooInt().HasFooInt); - TestOneof2 message2 = builder.Build(); - Assert.IsFalse(message2.HasFooInt); - Assert.AreEqual(message2.FooInt, 0); - } - - [Test] - public void TestOneofTypes_Enum() - { - TestOneof2.Builder builder = TestOneof2.CreateBuilder(); - Assert.AreEqual(builder.FooEnum, TestOneof2.Types.NestedEnum.FOO); - Assert.IsTrue(builder.SetFooEnum(TestOneof2.Types.NestedEnum.BAR).HasFooEnum); - Assert.AreEqual(builder.FooEnum, TestOneof2.Types.NestedEnum.BAR); - TestOneof2 message = builder.BuildPartial(); - Assert.IsTrue(message.HasFooEnum); - Assert.AreEqual(message.FooEnum, TestOneof2.Types.NestedEnum.BAR); - - Assert.IsFalse(builder.ClearFooEnum().HasFooEnum); - TestOneof2 message2 = builder.Build(); - Assert.IsFalse(message2.HasFooEnum); - Assert.AreEqual(message2.FooEnum, TestOneof2.Types.NestedEnum.FOO); - } - - [Test] - public void TestOneofTypes_String() - { - TestOneof2.Builder builder = TestOneof2.CreateBuilder(); - Assert.AreEqual(builder.FooString, ""); - Assert.IsTrue(builder.SetFooString("foo").HasFooString); - Assert.AreEqual(builder.FooString, "foo"); - TestOneof2 message = builder.BuildPartial(); - Assert.IsTrue(message.HasFooString); - Assert.AreEqual(message.FooString, "foo"); - - Assert.IsFalse(builder.ClearFooString().HasFooString); - TestOneof2 message2 = builder.Build(); - Assert.IsFalse(message2.HasFooString); - Assert.AreEqual(message2.FooString, ""); - - builder.SetFooInt(123); - Assert.AreEqual(builder.FooString, ""); - Assert.AreEqual(builder.FooInt, 123); - message = builder.Build(); - Assert.AreEqual(message.FooString, ""); - Assert.AreEqual(message.FooInt, 123); - } - - [Test] - public void TestOneofTypes_Message() - { - TestOneof2.Builder builder = TestOneof2.CreateBuilder(); - Assert.AreEqual(builder.FooMessage.QuxInt, 0); - builder.SetFooMessage(TestOneof2.Types.NestedMessage.CreateBuilder().SetQuxInt(234).Build()); - Assert.IsTrue(builder.HasFooMessage); - Assert.AreEqual(builder.FooMessage.QuxInt, 234); - TestOneof2 message = builder.BuildPartial(); - Assert.IsTrue(message.HasFooMessage); - Assert.AreEqual(message.FooMessage.QuxInt, 234); - - Assert.IsFalse(builder.ClearFooMessage().HasFooMessage); - message = builder.Build(); - Assert.IsFalse(message.HasFooMessage); - Assert.AreEqual(message.FooMessage.QuxInt, 0); - - builder = TestOneof2.CreateBuilder(); - Assert.IsFalse(builder.HasFooMessage); - builder.SetFooMessage(TestOneof2.Types.NestedMessage.CreateBuilder().SetQuxInt(123)); - Assert.IsTrue(builder.HasFooMessage); - Assert.AreEqual(builder.FooMessage.QuxInt, 123); - message = builder.Build(); - Assert.IsTrue(message.HasFooMessage); - Assert.AreEqual(message.FooMessage.QuxInt, 123); - } - - [Test] - public void TestOneofMerge_Primitive() - { - TestOneof2.Builder builder = TestOneof2.CreateBuilder(); - TestOneof2 message = builder.SetFooInt(123).Build(); - TestOneof2 message2 = TestOneof2.CreateBuilder().MergeFrom(message).Build(); - Assert.IsTrue(message2.HasFooInt); - Assert.AreEqual(message2.FooInt, 123); - } - - [Test] - public void TestOneofMerge_String() - { - TestOneof2.Builder builder = TestOneof2.CreateBuilder(); - TestOneof2 message = builder.SetFooString("foo").Build(); - TestOneof2 message2 = TestOneof2.CreateBuilder().MergeFrom(message).Build(); - Assert.IsTrue(message2.HasFooString); - Assert.AreEqual(message2.FooString, "foo"); - } - - [Test] - public void TestOneofMerge_Enum() - { - TestOneof2.Builder builder = TestOneof2.CreateBuilder(); - TestOneof2 message = builder.SetFooEnum(TestOneof2.Types.NestedEnum.BAR).Build(); - TestOneof2 message2 = TestOneof2.CreateBuilder().MergeFrom(message).Build(); - Assert.IsTrue(message2.HasFooEnum); - Assert.AreEqual(message2.FooEnum, TestOneof2.Types.NestedEnum.BAR); - } - - public void TestOneofMerge_message() - { - TestOneof2.Builder builder = TestOneof2.CreateBuilder(); - TestOneof2 message = builder.SetFooMessage( - TestOneof2.Types.NestedMessage.CreateBuilder().SetQuxInt(234).Build()).Build(); - TestOneof2 message2 = TestOneof2.CreateBuilder().MergeFrom(message).Build(); - Assert.IsTrue(message2.HasFooMessage); - Assert.AreEqual(message2.FooMessage.QuxInt, 234); - } - - [Test] - public void TestOneofMergeMixed() - { - TestOneof2.Builder builder = TestOneof2.CreateBuilder(); - TestOneof2 message = builder.SetFooEnum(TestOneof2.Types.NestedEnum.BAR).Build(); - TestOneof2 message2 = - TestOneof2.CreateBuilder().SetFooString("foo").MergeFrom(message).Build(); - Assert.IsFalse(message2.HasFooString); - Assert.IsTrue(message2.HasFooEnum); - Assert.AreEqual(message2.FooEnum, TestOneof2.Types.NestedEnum.BAR); - } - - [Test] - public void TestOneofSerialization_Primitive() - { - TestOneof2.Builder builder = TestOneof2.CreateBuilder(); - TestOneof2 message = builder.SetFooInt(123).Build(); - ByteString serialized = message.ToByteString(); - TestOneof2 message2 = TestOneof2.ParseFrom(serialized); - Assert.IsTrue(message2.HasFooInt); - Assert.AreEqual(message2.FooInt, 123); - } - - [Test] - public void TestOneofSerialization_String() - { - TestOneof2.Builder builder = TestOneof2.CreateBuilder(); - TestOneof2 message = builder.SetFooString("foo").Build(); - ByteString serialized = message.ToByteString(); - TestOneof2 message2 = TestOneof2.ParseFrom(serialized); - Assert.IsTrue(message2.HasFooString); - Assert.AreEqual(message2.FooString, "foo"); - } - - [Test] - public void TestOneofSerialization_Enum() - { - TestOneof2.Builder builder = TestOneof2.CreateBuilder(); - TestOneof2 message = builder.SetFooEnum(TestOneof2.Types.NestedEnum.BAR).Build(); - ByteString serialized = message.ToByteString(); - TestOneof2 message2 = TestOneof2.ParseFrom(serialized); - Assert.IsTrue(message2.HasFooEnum); - Assert.AreEqual(message2.FooEnum, TestOneof2.Types.NestedEnum.BAR); - } - - [Test] - public void TestOneofSerialization_Message() - { - TestOneof2.Builder builder = TestOneof2.CreateBuilder(); - TestOneof2 message = builder.SetFooMessage( - TestOneof2.Types.NestedMessage.CreateBuilder().SetQuxInt(234).Build()).Build(); - ByteString serialized = message.ToByteString(); - TestOneof2 message2 = TestOneof2.ParseFrom(serialized); - Assert.IsTrue(message2.HasFooMessage); - Assert.AreEqual(message2.FooMessage.QuxInt, 234); + public void DefaultValues() + { + // Single fields + var message = new TestAllTypes(); + Assert.AreEqual(false, message.SingleBool); + Assert.AreEqual(ByteString.Empty, message.SingleBytes); + Assert.AreEqual(0.0, message.SingleDouble); + Assert.AreEqual(0, message.SingleFixed32); + Assert.AreEqual(0L, message.SingleFixed64); + Assert.AreEqual(0.0f, message.SingleFloat); + Assert.AreEqual(ForeignEnum.FOREIGN_UNSPECIFIED, message.SingleForeignEnum); + Assert.IsNull(message.SingleForeignMessage); + Assert.AreEqual(ImportEnum.IMPORT_ENUM_UNSPECIFIED, message.SingleImportEnum); + Assert.IsNull(message.SingleImportMessage); + Assert.AreEqual(0, message.SingleInt32); + Assert.AreEqual(0L, message.SingleInt64); + Assert.AreEqual(TestAllTypes.Types.NestedEnum.NESTED_ENUM_UNSPECIFIED, message.SingleNestedEnum); + Assert.IsNull(message.SingleNestedMessage); + Assert.IsNull(message.SinglePublicImportMessage); + Assert.AreEqual(0, message.SingleSfixed32); + Assert.AreEqual(0L, message.SingleSfixed64); + Assert.AreEqual(0, message.SingleSint32); + Assert.AreEqual(0L, message.SingleSint64); + Assert.AreEqual("", message.SingleString); + Assert.AreEqual(0U, message.SingleUint32); + Assert.AreEqual(0UL, message.SingleUint64); + + // Repeated fields + Assert.AreEqual(0, message.RepeatedBool.Count); + Assert.AreEqual(0, message.RepeatedBytes.Count); + Assert.AreEqual(0, message.RepeatedDouble.Count); + Assert.AreEqual(0, message.RepeatedFixed32.Count); + Assert.AreEqual(0, message.RepeatedFixed64.Count); + Assert.AreEqual(0, message.RepeatedFloat.Count); + Assert.AreEqual(0, message.RepeatedForeignEnum.Count); + Assert.AreEqual(0, message.RepeatedForeignMessage.Count); + Assert.AreEqual(0, message.RepeatedImportEnum.Count); + Assert.AreEqual(0, message.RepeatedImportMessage.Count); + Assert.AreEqual(0, message.RepeatedNestedEnum.Count); + Assert.AreEqual(0, message.RepeatedNestedMessage.Count); + Assert.AreEqual(0, message.RepeatedPublicImportMessage.Count); + Assert.AreEqual(0, message.RepeatedSfixed32.Count); + Assert.AreEqual(0, message.RepeatedSfixed64.Count); + Assert.AreEqual(0, message.RepeatedSint32.Count); + Assert.AreEqual(0, message.RepeatedSint64.Count); + Assert.AreEqual(0, message.RepeatedString.Count); + Assert.AreEqual(0, message.RepeatedUint32.Count); + Assert.AreEqual(0, message.RepeatedUint64.Count); + + // Oneof fields + Assert.AreEqual(TestAllTypes.OneofFieldOneofCase.None, message.OneofFieldCase); + Assert.AreEqual(0, message.OneofUint32); + Assert.AreEqual("", message.OneofString); + Assert.AreEqual(ByteString.Empty, message.OneofBytes); + Assert.IsNull(message.OneofNestedMessage); + } + + [Test] + public void RoundTrip_Empty() + { + var message = new TestAllTypes(); + // Without setting any values, there's nothing to write. + byte[] bytes = message.ToByteArray(); + Assert.AreEqual(0, bytes.Length); + TestAllTypes parsed = TestAllTypes.Parser.ParseFrom(bytes); + Assert.AreEqual(message, parsed); + } + + [Test] + public void RoundTrip_SingleValues() + { + var message = new TestAllTypes + { + SingleBool = true, + SingleBytes = ByteString.CopyFrom(new byte[] { 1, 2, 3, 4 }), + SingleDouble = 23.5, + SingleFixed32 = 23, + SingleFixed64 = 1234567890123, + SingleFloat = 12.25f, + SingleForeignEnum = ForeignEnum.FOREIGN_BAR, + SingleForeignMessage = new ForeignMessage { C = 10 }, + SingleImportEnum = ImportEnum.IMPORT_BAZ, + SingleImportMessage = new ImportMessage { D = 20 }, + SingleInt32 = 100, + SingleInt64 = 3210987654321, + SingleNestedEnum = TestAllTypes.Types.NestedEnum.FOO, + SingleNestedMessage = new TestAllTypes.Types.NestedMessage { Bb = 35 }, + SinglePublicImportMessage = new PublicImportMessage { E = 54 }, + SingleSfixed32 = -123, + SingleSfixed64 = -12345678901234, + SingleSint32 = -456, + SingleSint64 = -12345678901235, + SingleString = "test", + SingleUint32 = uint.MaxValue, + SingleUint64 = ulong.MaxValue + }; + + byte[] bytes = message.ToByteArray(); + TestAllTypes parsed = TestAllTypes.Parser.ParseFrom(bytes); + Assert.AreEqual(message, parsed); + } + + [Test] + public void RoundTrip_RepeatedValues() + { + var message = new TestAllTypes + { + RepeatedBool = { true, false }, + RepeatedBytes = { ByteString.CopyFrom(new byte[] { 1, 2, 3, 4 }), ByteString.CopyFrom(new byte[] { 5, 6 }) }, + RepeatedDouble = { -12.25, 23.5 }, + RepeatedFixed32 = { uint.MaxValue, 23 }, + RepeatedFixed64 = { ulong.MaxValue, 1234567890123 }, + RepeatedFloat = { 100f, 12.25f }, + RepeatedForeignEnum = { ForeignEnum.FOREIGN_FOO, ForeignEnum.FOREIGN_BAR }, + RepeatedForeignMessage = { new ForeignMessage(), new ForeignMessage { C = 10 } }, + RepeatedImportEnum = { ImportEnum.IMPORT_BAZ, ImportEnum.IMPORT_ENUM_UNSPECIFIED }, + RepeatedImportMessage = { new ImportMessage { D = 20 }, new ImportMessage { D = 25 } }, + RepeatedInt32 = { 100, 200 }, + RepeatedInt64 = { 3210987654321, long.MaxValue }, + RepeatedNestedEnum = { TestAllTypes.Types.NestedEnum.FOO, TestAllTypes.Types.NestedEnum.NEG }, + RepeatedNestedMessage = { new TestAllTypes.Types.NestedMessage { Bb = 35 }, new TestAllTypes.Types.NestedMessage { Bb = 10 } }, + RepeatedPublicImportMessage = { new PublicImportMessage { E = 54 }, new PublicImportMessage { E = -1 } }, + RepeatedSfixed32 = { -123, 123 }, + RepeatedSfixed64 = { -12345678901234, 12345678901234 }, + RepeatedSint32 = { -456, 100 }, + RepeatedSint64 = { -12345678901235, 123 }, + RepeatedString = { "foo", "bar" }, + RepeatedUint32 = { uint.MaxValue, uint.MinValue }, + RepeatedUint64 = { ulong.MaxValue, uint.MinValue } + }; + + byte[] bytes = message.ToByteArray(); + TestAllTypes parsed = TestAllTypes.Parser.ParseFrom(bytes); + Assert.AreEqual(message, parsed); } } -} \ No newline at end of file +} diff --git a/csharp/src/ProtocolBuffers.Test/IssuesTest.cs b/csharp/src/ProtocolBuffers.Test/IssuesTest.cs index ce7e5f09..87960aab 100644 --- a/csharp/src/ProtocolBuffers.Test/IssuesTest.cs +++ b/csharp/src/ProtocolBuffers.Test/IssuesTest.cs @@ -34,13 +34,12 @@ #endregion - -using Google.ProtocolBuffers.Descriptors; +using Google.Protobuf.Descriptors; using UnitTest.Issues.TestProtos; using NUnit.Framework; -namespace Google.ProtocolBuffers +namespace Google.Protobuf { /// /// Tests for issues which aren't easily compartmentalized into other unit tests. @@ -51,10 +50,11 @@ namespace Google.ProtocolBuffers [Test] public void FieldCalledItem() { - ItemField message = new ItemField.Builder { Item = 3 }.Build(); + ItemField message = new ItemField { Item = 3 }; FieldDescriptor field = ItemField.Descriptor.FindFieldByName("item"); Assert.NotNull(field); - Assert.AreEqual(3, (int)message[field]); + // TODO(jonskeet): Reflection... + // Assert.AreEqual(3, (int)message[field]); } } } diff --git a/csharp/src/ProtocolBuffers.Test/MessageStreamIteratorTest.cs b/csharp/src/ProtocolBuffers.Test/MessageStreamIteratorTest.cs deleted file mode 100644 index 4754ce60..00000000 --- a/csharp/src/ProtocolBuffers.Test/MessageStreamIteratorTest.cs +++ /dev/null @@ -1,90 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.Collections.Generic; -using System.IO; -using Google.ProtocolBuffers.TestProtos; -using NUnit.Framework; -using NestedMessage = Google.ProtocolBuffers.TestProtos.TestAllTypes.Types.NestedMessage; - -namespace Google.ProtocolBuffers -{ - public class MessageStreamIteratorTest - { - [Test] - public void ThreeMessagesInMemory() - { - MemoryStream stream = new MemoryStream(MessageStreamWriterTest.ThreeMessageData); - IEnumerable iterator = MessageStreamIterator.FromStreamProvider(() => stream); - List messages = new List(iterator); - - Assert.AreEqual(3, messages.Count); - Assert.AreEqual(5, messages[0].Bb); - Assert.AreEqual(1500, messages[1].Bb); - Assert.IsFalse(messages[2].HasBb); - } - - [Test] - public void ManyMessagesShouldNotTriggerSizeAlert() - { - int messageSize = TestUtil.GetAllSet().SerializedSize; - // Enough messages to trigger the alert unless we've reset the size - // Note that currently we need to make this big enough to copy two whole buffers, - // as otherwise when we refill the buffer the second type, the alert triggers instantly. - int correctCount = (CodedInputStream.BufferSize*2)/messageSize + 1; - using (MemoryStream stream = new MemoryStream()) - { - MessageStreamWriter writer = new MessageStreamWriter(stream); - for (int i = 0; i < correctCount; i++) - { - writer.Write(TestUtil.GetAllSet()); - } - writer.Flush(); - - stream.Position = 0; - - int count = 0; - foreach (var message in MessageStreamIterator.FromStreamProvider(() => stream) - .WithSizeLimit(CodedInputStream.BufferSize*2)) - { - count++; - TestUtil.AssertAllFieldsSet(message); - } - Assert.AreEqual(correctCount, count); - } - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers.Test/MessageStreamWriterTest.cs b/csharp/src/ProtocolBuffers.Test/MessageStreamWriterTest.cs deleted file mode 100644 index 030804ee..00000000 --- a/csharp/src/ProtocolBuffers.Test/MessageStreamWriterTest.cs +++ /dev/null @@ -1,78 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.IO; -using NUnit.Framework; -using NestedMessage = Google.ProtocolBuffers.TestProtos.TestAllTypes.Types.NestedMessage; - -namespace Google.ProtocolBuffers -{ - public class MessageStreamWriterTest - { - internal static readonly byte[] ThreeMessageData = new byte[] - { - (1 << 3) | 2, 2, - // Field 1, 2 bytes long (first message) - (1 << 3) | 0, 5, // Field 1, value 5 - (1 << 3) | 2, 3, - // Field 1, 3 bytes long (second message) - (1 << 3) | 0, (1500 & 0x7f) | 0x80, 1500 >> 7, - // Field 1, value 1500 - (1 << 3) | 2, 0, // Field 1, no data (third message) - }; - - [Test] - public void ThreeMessages() - { - NestedMessage message1 = new NestedMessage.Builder {Bb = 5}.Build(); - NestedMessage message2 = new NestedMessage.Builder {Bb = 1500}.Build(); - NestedMessage message3 = new NestedMessage.Builder().Build(); - - byte[] data; - using (MemoryStream stream = new MemoryStream()) - { - MessageStreamWriter writer = new MessageStreamWriter(stream); - writer.Write(message1); - writer.Write(message2); - writer.Write(message3); - writer.Flush(); - data = stream.ToArray(); - } - - TestUtil.AssertEqualBytes(ThreeMessageData, data); - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers.Test/MessageTest.cs b/csharp/src/ProtocolBuffers.Test/MessageTest.cs deleted file mode 100644 index e746c01a..00000000 --- a/csharp/src/ProtocolBuffers.Test/MessageTest.cs +++ /dev/null @@ -1,344 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System.IO; -using Google.ProtocolBuffers.Descriptors; -using Google.ProtocolBuffers.TestProtos; -using NUnit.Framework; - -namespace Google.ProtocolBuffers -{ - /// - /// Miscellaneous tests for message operations that apply to both - /// generated and dynamic messages. - /// - public class MessageTest - { - // ================================================================= - // Message-merging tests. - - private static readonly TestAllTypes MergeSource = new TestAllTypes.Builder - { - OptionalInt32 = 1, - OptionalString = "foo", - OptionalForeignMessage = - ForeignMessage.DefaultInstance, - }.AddRepeatedString("bar").Build(); - - private static readonly TestAllTypes MergeDest = new TestAllTypes.Builder - { - OptionalInt64 = 2, - OptionalString = "baz", - OptionalForeignMessage = - new ForeignMessage.Builder {C = 3}.Build(), - }.AddRepeatedString("qux").Build(); - - private const string MergeResultText = - "optional_int32: 1\n" + - "optional_int64: 2\n" + - "optional_string: \"foo\"\n" + - "optional_foreign_message {\n" + - " c: 3\n" + - "}\n" + - "repeated_string: \"qux\"\n" + - "repeated_string: \"bar\"\n"; - - [Test] - public void MergeFrom() - { - TestAllTypes result = TestAllTypes.CreateBuilder(MergeDest).MergeFrom(MergeSource).Build(); - - Assert.AreEqual(MergeResultText, result.ToString()); - } - - /// - /// Test merging a DynamicMessage into a GeneratedMessage. - /// As long as they have the same descriptor, this should work, but it is an - /// entirely different code path. - /// - [Test] - public void MergeFromDynamic() - { - TestAllTypes result = (TestAllTypes) TestAllTypes.CreateBuilder(MergeDest) - .MergeFrom(DynamicMessage.CreateBuilder(MergeSource).Build()) - .Build(); - - Assert.AreEqual(MergeResultText, result.ToString()); - } - - /// - /// Test merging two DynamicMessages. - /// - [Test] - public void DynamicMergeFrom() - { - DynamicMessage result = (DynamicMessage) DynamicMessage.CreateBuilder(MergeDest) - .MergeFrom( - (DynamicMessage) - DynamicMessage.CreateBuilder(MergeSource).Build()) - .Build(); - - Assert.AreEqual(MergeResultText, result.ToString()); - } - - // ================================================================= - // Required-field-related tests. - - private static readonly TestRequired TestRequiredUninitialized = TestRequired.DefaultInstance; - - private static readonly TestRequired TestRequiredInitialized = new TestRequired.Builder - { - A = 1, - B = 2, - C = 3 - }.Build(); - - [Test] - public void Initialization() - { - TestRequired.Builder builder = TestRequired.CreateBuilder(); - - Assert.IsFalse(builder.IsInitialized); - builder.A = 1; - Assert.IsFalse(builder.IsInitialized); - builder.B = 1; - Assert.IsFalse(builder.IsInitialized); - builder.C = 1; - Assert.IsTrue(builder.IsInitialized); - } - - [Test] - public void UninitializedBuilderToString() - { - TestRequired.Builder builder = TestRequired.CreateBuilder().SetA(1); - Assert.AreEqual("a: 1\n", builder.ToString()); - } - - [Test] - public void RequiredForeign() - { - TestRequiredForeign.Builder builder = TestRequiredForeign.CreateBuilder(); - - Assert.IsTrue(builder.IsInitialized); - - builder.SetOptionalMessage(TestRequiredUninitialized); - Assert.IsFalse(builder.IsInitialized); - - builder.SetOptionalMessage(TestRequiredInitialized); - Assert.IsTrue(builder.IsInitialized); - - builder.AddRepeatedMessage(TestRequiredUninitialized); - Assert.IsFalse(builder.IsInitialized); - - builder.SetRepeatedMessage(0, TestRequiredInitialized); - Assert.IsTrue(builder.IsInitialized); - } - - [Test] - public void RequiredExtension() - { - TestAllExtensions.Builder builder = TestAllExtensions.CreateBuilder(); - - Assert.IsTrue(builder.IsInitialized); - - builder.SetExtension(TestRequired.Single, TestRequiredUninitialized); - Assert.IsFalse(builder.IsInitialized); - - builder.SetExtension(TestRequired.Single, TestRequiredInitialized); - Assert.IsTrue(builder.IsInitialized); - - builder.AddExtension(TestRequired.Multi, TestRequiredUninitialized); - Assert.IsFalse(builder.IsInitialized); - - builder.SetExtension(TestRequired.Multi, 0, TestRequiredInitialized); - Assert.IsTrue(builder.IsInitialized); - } - - [Test] - public void RequiredDynamic() - { - MessageDescriptor descriptor = TestRequired.Descriptor; - DynamicMessage.Builder builder = DynamicMessage.CreateBuilder(descriptor); - - Assert.IsFalse(builder.IsInitialized); - builder[descriptor.FindDescriptor("a")] = 1; - Assert.IsFalse(builder.IsInitialized); - builder[descriptor.FindDescriptor("b")] = 1; - Assert.IsFalse(builder.IsInitialized); - builder[descriptor.FindDescriptor("c")] = 1; - Assert.IsTrue(builder.IsInitialized); - } - - [Test] - public void RequiredDynamicForeign() - { - MessageDescriptor descriptor = TestRequiredForeign.Descriptor; - DynamicMessage.Builder builder = DynamicMessage.CreateBuilder(descriptor); - - Assert.IsTrue(builder.IsInitialized); - - builder[descriptor.FindDescriptor("optional_message")] = TestRequiredUninitialized; - Assert.IsFalse(builder.IsInitialized); - - builder[descriptor.FindDescriptor("optional_message")] = TestRequiredInitialized; - Assert.IsTrue(builder.IsInitialized); - - builder.AddRepeatedField(descriptor.FindDescriptor("repeated_message"), - TestRequiredUninitialized); - Assert.IsFalse(builder.IsInitialized); - - builder.SetRepeatedField(descriptor.FindDescriptor("repeated_message"), 0, - TestRequiredInitialized); - Assert.IsTrue(builder.IsInitialized); - } - - [Test] - public void UninitializedException() - { - var e = Assert.Throws(() => TestRequired.CreateBuilder().Build()); - Assert.AreEqual("Message missing required fields: a, b, c", e.Message); - } - - [Test] - public void BuildPartial() - { - // We're mostly testing that no exception is thrown. - TestRequired message = TestRequired.CreateBuilder().BuildPartial(); - Assert.IsFalse(message.IsInitialized); - } - - [Test] - public void NestedUninitializedException() - { - var e = Assert.Throws(() => TestRequiredForeign.CreateBuilder() - .SetOptionalMessage(TestRequiredUninitialized) - .AddRepeatedMessage(TestRequiredUninitialized) - .AddRepeatedMessage(TestRequiredUninitialized) - .Build()); - Assert.AreEqual( - "Message missing required fields: " + - "optional_message.a, " + - "optional_message.b, " + - "optional_message.c, " + - "repeated_message[0].a, " + - "repeated_message[0].b, " + - "repeated_message[0].c, " + - "repeated_message[1].a, " + - "repeated_message[1].b, " + - "repeated_message[1].c", - e.Message); - } - - [Test] - public void BuildNestedPartial() - { - // We're mostly testing that no exception is thrown. - TestRequiredForeign message = - TestRequiredForeign.CreateBuilder() - .SetOptionalMessage(TestRequiredUninitialized) - .AddRepeatedMessage(TestRequiredUninitialized) - .AddRepeatedMessage(TestRequiredUninitialized) - .BuildPartial(); - Assert.IsFalse(message.IsInitialized); - } - - [Test] - public void ParseUninitialized() - { - var e = Assert.Throws(() => TestRequired.ParseFrom(ByteString.Empty)); - Assert.AreEqual("Message missing required fields: a, b, c", e.Message); - } - - [Test] - public void ParseNestedUnititialized() - { - ByteString data = - TestRequiredForeign.CreateBuilder() - .SetOptionalMessage(TestRequiredUninitialized) - .AddRepeatedMessage(TestRequiredUninitialized) - .AddRepeatedMessage(TestRequiredUninitialized) - .BuildPartial().ToByteString(); - - var e = Assert.Throws(() => TestRequiredForeign.ParseFrom(data)); - Assert.AreEqual( - "Message missing required fields: " + - "optional_message.a, " + - "optional_message.b, " + - "optional_message.c, " + - "repeated_message[0].a, " + - "repeated_message[0].b, " + - "repeated_message[0].c, " + - "repeated_message[1].a, " + - "repeated_message[1].b, " + - "repeated_message[1].c", - e.Message); - } - - [Test] - public void DynamicUninitializedException() - { - var e = Assert.Throws(() => DynamicMessage.CreateBuilder(TestRequired.Descriptor).Build()); - Assert.AreEqual("Message missing required fields: a, b, c", e.Message); - } - - [Test] - public void DynamicBuildPartial() - { - // We're mostly testing that no exception is thrown. - DynamicMessage message = DynamicMessage.CreateBuilder(TestRequired.Descriptor).BuildPartial(); - Assert.IsFalse(message.Initialized); - } - - [Test] - public void DynamicParseUnititialized() - { - MessageDescriptor descriptor = TestRequired.Descriptor; - var e = Assert.Throws(() => DynamicMessage.ParseFrom(descriptor, ByteString.Empty)); - Assert.AreEqual("Message missing required fields: a, b, c", e.Message); - } - - [Test] - public void PackedTypesWrittenDirectlyToStream() - { - TestPackedTypes message = new TestPackedTypes.Builder {PackedInt32List = {0, 1, 2}}.Build(); - MemoryStream stream = new MemoryStream(); - message.WriteTo(stream); - stream.Position = 0; - TestPackedTypes readMessage = TestPackedTypes.ParseFrom(stream); - Assert.AreEqual(message, readMessage); - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers.Test/MessageUtilTest.cs b/csharp/src/ProtocolBuffers.Test/MessageUtilTest.cs deleted file mode 100644 index 72909660..00000000 --- a/csharp/src/ProtocolBuffers.Test/MessageUtilTest.cs +++ /dev/null @@ -1,82 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using Google.ProtocolBuffers.TestProtos; -using NUnit.Framework; - -namespace Google.ProtocolBuffers -{ - public class MessageUtilTest - { - [Test] - public void NullTypeName() - { - Assert.Throws(() => MessageUtil.GetDefaultMessage((string) null)); - } - - [Test] - public void InvalidTypeName() - { - Assert.Throws(() => MessageUtil.GetDefaultMessage("invalidtypename")); - } - - [Test] - public void ValidTypeName() - { - Assert.AreSame(TestAllTypes.DefaultInstance, - MessageUtil.GetDefaultMessage(typeof(TestAllTypes).AssemblyQualifiedName)); - } - - [Test] - public void NullType() - { - Assert.Throws(() => MessageUtil.GetDefaultMessage((Type)null)); - } - - [Test] - public void NonMessageType() - { - Assert.Throws(() => MessageUtil.GetDefaultMessage(typeof(string))); - } - - [Test] - public void ValidType() - { - Assert.AreSame(TestAllTypes.DefaultInstance, MessageUtil.GetDefaultMessage(typeof(TestAllTypes))); - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers.Test/NameHelpersTest.cs b/csharp/src/ProtocolBuffers.Test/NameHelpersTest.cs deleted file mode 100644 index edd3ccd9..00000000 --- a/csharp/src/ProtocolBuffers.Test/NameHelpersTest.cs +++ /dev/null @@ -1,81 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using NUnit.Framework; - -namespace Google.ProtocolBuffers -{ - public class NameHelpersTest - { - [Test] - public void UnderscoresToPascalCase() - { - Assert.AreEqual("FooBar", NameHelpers.UnderscoresToPascalCase("Foo_bar")); - Assert.AreEqual("FooBar", NameHelpers.UnderscoresToPascalCase("foo_bar")); - Assert.AreEqual("Foo0Bar", NameHelpers.UnderscoresToPascalCase("Foo0bar")); - Assert.AreEqual("FooBar", NameHelpers.UnderscoresToPascalCase("Foo_+_Bar")); - - Assert.AreEqual("Bar", NameHelpers.UnderscoresToPascalCase("__+bar")); - Assert.AreEqual("Bar", NameHelpers.UnderscoresToPascalCase("bar_")); - Assert.AreEqual("_0Bar", NameHelpers.UnderscoresToPascalCase("_0bar")); - Assert.AreEqual("_1Bar", NameHelpers.UnderscoresToPascalCase("_1_bar")); - } - - [Test] - public void UnderscoresToCamelCase() - { - Assert.AreEqual("fooBar", NameHelpers.UnderscoresToCamelCase("Foo_bar")); - Assert.AreEqual("fooBar", NameHelpers.UnderscoresToCamelCase("foo_bar")); - Assert.AreEqual("foo0Bar", NameHelpers.UnderscoresToCamelCase("Foo0bar")); - Assert.AreEqual("fooBar", NameHelpers.UnderscoresToCamelCase("Foo_+_Bar")); - - Assert.AreEqual("bar", NameHelpers.UnderscoresToCamelCase("__+bar")); - Assert.AreEqual("bar", NameHelpers.UnderscoresToCamelCase("bar_")); - Assert.AreEqual("_0Bar", NameHelpers.UnderscoresToCamelCase("_0bar")); - Assert.AreEqual("_1Bar", NameHelpers.UnderscoresToCamelCase("_1_bar")); - } - - [Test] - public void StripSuffix() - { - string text = "FooBar"; - Assert.IsFalse(NameHelpers.StripSuffix(ref text, "Foo")); - Assert.AreEqual("FooBar", text); - Assert.IsTrue(NameHelpers.StripSuffix(ref text, "Bar")); - Assert.AreEqual("Foo", text); - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers.Test/ProtocolBuffers.Test.csproj b/csharp/src/ProtocolBuffers.Test/ProtocolBuffers.Test.csproj index b4c562d1..31095a5b 100644 --- a/csharp/src/ProtocolBuffers.Test/ProtocolBuffers.Test.csproj +++ b/csharp/src/ProtocolBuffers.Test/ProtocolBuffers.Test.csproj @@ -8,8 +8,8 @@ {DD01ED24-3750-4567-9A23-1DB676A15610} Library Properties - Google.ProtocolBuffers - Google.ProtocolBuffers.Test + Google.Protobuf + Google.Protobuf.Test v4.5 512 true @@ -71,79 +71,37 @@ - - - - - - - - - - - - - - - - - - - + + + + - - - - - - + - - - - - - - - - - - - - - - - - - - {231391AF-449C-4a39-986C-AD7F270F4750} - ProtocolBuffers.Serialization - {6908BDCE-D925-43F3-94AC-A531E6DF2591} ProtocolBuffers - - - - + + + - + \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers/SortedList.cs b/csharp/src/ProtocolBuffers/SortedList.cs deleted file mode 100644 index 2dd7da92..00000000 --- a/csharp/src/ProtocolBuffers/SortedList.cs +++ /dev/null @@ -1,167 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -#if NOSORTEDLIST -using System.Collections; -using System.Collections.Generic; - -namespace Google.ProtocolBuffers -{ - /// - /// Dictionary implementation which always yields keys in sorted order. - /// This is not particularly efficient: it wraps a normal dictionary - /// for most operations, but sorts by key when either iterating or - /// fetching the Keys/Values properties. - /// - internal sealed class SortedList : IDictionary - { - private readonly IDictionary wrapped = new Dictionary(); - - public SortedList() - { - } - - public SortedList(IDictionary dictionary) - { - foreach (KeyValuePair entry in dictionary) - { - Add(entry.Key, entry.Value); - } - } - - public void Add(TKey key, TValue value) - { - wrapped.Add(key, value); - } - - public bool ContainsKey(TKey key) - { - return wrapped.ContainsKey(key); - } - - public ICollection Keys - { - get - { - List keys = new List(wrapped.Count); - foreach (var pair in this) - { - keys.Add(pair.Key); - } - return keys; - } - } - - public bool Remove(TKey key) - { - return wrapped.Remove(key); - } - - public bool TryGetValue(TKey key, out TValue value) - { - return wrapped.TryGetValue(key, out value); - } - - public ICollection Values - { - get - { - List values = new List(wrapped.Count); - foreach (var pair in this) - { - values.Add(pair.Value); - } - return values; - } - } - - public TValue this[TKey key] - { - get { return wrapped[key]; } - set { wrapped[key] = value; } - } - - public void Add(KeyValuePair item) - { - wrapped.Add(item); - } - - public void Clear() - { - wrapped.Clear(); - } - - public bool Contains(KeyValuePair item) - { - return wrapped.Contains(item); - } - - public void CopyTo(KeyValuePair[] array, int arrayIndex) - { - wrapped.CopyTo(array, arrayIndex); - } - - public int Count - { - get { return wrapped.Count; } - } - - public bool IsReadOnly - { - get { return wrapped.IsReadOnly; } - } - - public bool Remove(KeyValuePair item) - { - return wrapped.Remove(item); - } - - public IEnumerator> GetEnumerator() - { - IComparer comparer = Comparer.Default; - var list = new List>(wrapped); - list.Sort((x, y) => comparer.Compare(x.Key, y.Key)); - return list.GetEnumerator(); - } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - } -} - -#endif \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers/TextFormat.cs b/csharp/src/ProtocolBuffers/TextFormat.cs deleted file mode 100644 index 6a9180f3..00000000 --- a/csharp/src/ProtocolBuffers/TextFormat.cs +++ /dev/null @@ -1,893 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Text; -using Google.ProtocolBuffers.Descriptors; - -namespace Google.ProtocolBuffers -{ - /// - /// Provides ASCII text formatting support for messages. - /// TODO(jonskeet): Support for alternative line endings. - /// (Easy to print, via TextGenerator. Not sure about parsing.) - /// - public static class TextFormat - { - /// - /// Outputs a textual representation of the Protocol Message supplied into - /// the parameter output. - /// - public static void Print(IMessage message, TextWriter output) - { - TextGenerator generator = new TextGenerator(output, "\n"); - Print(message, generator); - } - - /// - /// Outputs a textual representation of the Protocol Message builder supplied into - /// the parameter output. - /// - public static void Print(IBuilder builder, TextWriter output) - { - TextGenerator generator = new TextGenerator(output, "\n"); - Print(builder, generator); - } - - /// - /// Outputs a textual representation of to . - /// - public static void Print(UnknownFieldSet fields, TextWriter output) - { - TextGenerator generator = new TextGenerator(output, "\n"); - PrintUnknownFields(fields, generator); - } - - public static string PrintToString(IMessage message) - { - StringWriter text = new StringWriter(); - Print(message, text); - return text.ToString(); - } - - public static string PrintToString(IBuilder builder) - { - StringWriter text = new StringWriter(); - Print(builder, text); - return text.ToString(); - } - - public static string PrintToString(UnknownFieldSet fields) - { - StringWriter text = new StringWriter(); - Print(fields, text); - return text.ToString(); - } - - private static void Print(IMessage message, TextGenerator generator) - { - foreach (KeyValuePair entry in message.AllFields) - { - PrintField(entry.Key, entry.Value, generator); - } - PrintUnknownFields(message.UnknownFields, generator); - } - - private static void Print(IBuilder message, TextGenerator generator) - { - foreach (KeyValuePair entry in message.AllFields) - { - PrintField(entry.Key, entry.Value, generator); - } - PrintUnknownFields(message.UnknownFields, generator); - } - - internal static void PrintField(FieldDescriptor field, object value, TextGenerator generator) - { - if (field.IsRepeated) - { - // Repeated field. Print each element. - foreach (object element in (IEnumerable) value) - { - PrintSingleField(field, element, generator); - } - } - else - { - PrintSingleField(field, value, generator); - } - } - - private static void PrintSingleField(FieldDescriptor field, Object value, TextGenerator generator) - { - if (field.IsExtension) - { - generator.Print("["); - // We special-case MessageSet elements for compatibility with proto1. - if (field.ContainingType.Options.MessageSetWireFormat - && field.FieldType == FieldType.Message - && field.IsOptional - // object equality (TODO(jonskeet): Work out what this comment means!) - && field.ExtensionScope == field.MessageType) - { - generator.Print(field.MessageType.FullName); - } - else - { - generator.Print(field.FullName); - } - generator.Print("]"); - } - else - { - if (field.FieldType == FieldType.Group) - { - // Groups must be serialized with their original capitalization. - generator.Print(field.MessageType.Name); - } - else - { - generator.Print(field.Name); - } - } - - if (field.MappedType == MappedType.Message) - { - generator.Print(" {\n"); - generator.Indent(); - } - else - { - generator.Print(": "); - } - - PrintFieldValue(field, value, generator); - - if (field.MappedType == MappedType.Message) - { - generator.Outdent(); - generator.Print("}"); - } - generator.Print("\n"); - } - - private static void PrintFieldValue(FieldDescriptor field, object value, TextGenerator generator) - { - switch (field.FieldType) - { - // The Float and Double types must specify the "r" format to preserve their precision, otherwise, - // the double to/from string will trim the precision to 6 places. As with other numeric formats - // below, always use the invariant culture so it's predictable. - case FieldType.Float: - generator.Print(((float)value).ToString("r", FrameworkPortability.InvariantCulture)); - break; - case FieldType.Double: - generator.Print(((double)value).ToString("r", FrameworkPortability.InvariantCulture)); - break; - - case FieldType.Int32: - case FieldType.Int64: - case FieldType.SInt32: - case FieldType.SInt64: - case FieldType.SFixed32: - case FieldType.SFixed64: - case FieldType.UInt32: - case FieldType.UInt64: - case FieldType.Fixed32: - case FieldType.Fixed64: - // The simple Object.ToString converts using the current culture. - // We want to always use the invariant culture so it's predictable. - generator.Print(((IConvertible)value).ToString(FrameworkPortability.InvariantCulture)); - break; - case FieldType.Bool: - // Explicitly use the Java true/false - generator.Print((bool) value ? "true" : "false"); - break; - - case FieldType.String: - generator.Print("\""); - generator.Print(EscapeText((string) value)); - generator.Print("\""); - break; - - case FieldType.Bytes: - { - generator.Print("\""); - generator.Print(EscapeBytes((ByteString) value)); - generator.Print("\""); - break; - } - - case FieldType.Enum: - { - if (value is IEnumLite && !(value is EnumValueDescriptor)) - { - throw new NotSupportedException("Lite enumerations are not supported."); - } - generator.Print(((EnumValueDescriptor) value).Name); - break; - } - - case FieldType.Message: - case FieldType.Group: - if (value is IMessageLite && !(value is IMessage)) - { - throw new NotSupportedException("Lite messages are not supported."); - } - Print((IMessage) value, generator); - break; - } - } - - private static void PrintUnknownFields(UnknownFieldSet unknownFields, TextGenerator generator) - { - foreach (KeyValuePair entry in unknownFields.FieldDictionary) - { - String prefix = entry.Key.ToString() + ": "; - UnknownField field = entry.Value; - - foreach (ulong value in field.VarintList) - { - generator.Print(prefix); - generator.Print(value.ToString()); - generator.Print("\n"); - } - foreach (uint value in field.Fixed32List) - { - generator.Print(prefix); - generator.Print(string.Format("0x{0:x8}", value)); - generator.Print("\n"); - } - foreach (ulong value in field.Fixed64List) - { - generator.Print(prefix); - generator.Print(string.Format("0x{0:x16}", value)); - generator.Print("\n"); - } - foreach (ByteString value in field.LengthDelimitedList) - { - generator.Print(entry.Key.ToString()); - generator.Print(": \""); - generator.Print(EscapeBytes(value)); - generator.Print("\"\n"); - } - foreach (UnknownFieldSet value in field.GroupList) - { - generator.Print(entry.Key.ToString()); - generator.Print(" {\n"); - generator.Indent(); - PrintUnknownFields(value, generator); - generator.Outdent(); - generator.Print("}\n"); - } - } - } - - public static ulong ParseUInt64(string text) - { - return (ulong) ParseInteger(text, false, true); - } - - public static long ParseInt64(string text) - { - return ParseInteger(text, true, true); - } - - public static uint ParseUInt32(string text) - { - return (uint) ParseInteger(text, false, false); - } - - public static int ParseInt32(string text) - { - return (int) ParseInteger(text, true, false); - } - - public static float ParseFloat(string text) - { - switch (text) - { - case "-inf": - case "-infinity": - case "-inff": - case "-infinityf": - return float.NegativeInfinity; - case "inf": - case "infinity": - case "inff": - case "infinityf": - return float.PositiveInfinity; - case "nan": - case "nanf": - return float.NaN; - default: - return float.Parse(text, FrameworkPortability.InvariantCulture); - } - } - - public static double ParseDouble(string text) - { - switch (text) - { - case "-inf": - case "-infinity": - return double.NegativeInfinity; - case "inf": - case "infinity": - return double.PositiveInfinity; - case "nan": - return double.NaN; - default: - return double.Parse(text, FrameworkPortability.InvariantCulture); - } - } - - /// - /// Parses an integer in hex (leading 0x), decimal (no prefix) or octal (leading 0). - /// Only a negative sign is permitted, and it must come before the radix indicator. - /// - private static long ParseInteger(string text, bool isSigned, bool isLong) - { - string original = text; - bool negative = false; - if (text.StartsWith("-")) - { - if (!isSigned) - { - throw new FormatException("Number must be positive: " + original); - } - negative = true; - text = text.Substring(1); - } - - int radix = 10; - if (text.StartsWith("0x")) - { - radix = 16; - text = text.Substring(2); - } - else if (text.StartsWith("0")) - { - radix = 8; - } - - ulong result; - try - { - // Workaround for https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=278448 - // We should be able to use Convert.ToUInt64 for all cases. - result = radix == 10 ? ulong.Parse(text) : Convert.ToUInt64(text, radix); - } - catch (OverflowException) - { - // Convert OverflowException to FormatException so there's a single exception type this method can throw. - string numberDescription = string.Format("{0}-bit {1}signed integer", isLong ? 64 : 32, - isSigned ? "" : "un"); - throw new FormatException("Number out of range for " + numberDescription + ": " + original); - } - - if (negative) - { - ulong max = isLong ? 0x8000000000000000UL : 0x80000000L; - if (result > max) - { - string numberDescription = string.Format("{0}-bit signed integer", isLong ? 64 : 32); - throw new FormatException("Number out of range for " + numberDescription + ": " + original); - } - return -((long) result); - } - else - { - ulong max = isSigned - ? (isLong ? (ulong) long.MaxValue : int.MaxValue) - : (isLong ? ulong.MaxValue : uint.MaxValue); - if (result > max) - { - string numberDescription = string.Format("{0}-bit {1}signed integer", isLong ? 64 : 32, - isSigned ? "" : "un"); - throw new FormatException("Number out of range for " + numberDescription + ": " + original); - } - return (long) result; - } - } - - /// - /// Tests a character to see if it's an octal digit. - /// - private static bool IsOctal(char c) - { - return '0' <= c && c <= '7'; - } - - /// - /// Tests a character to see if it's a hex digit. - /// - private static bool IsHex(char c) - { - return ('0' <= c && c <= '9') || - ('a' <= c && c <= 'f') || - ('A' <= c && c <= 'F'); - } - - /// - /// Interprets a character as a digit (in any base up to 36) and returns the - /// numeric value. - /// - private static int ParseDigit(char c) - { - if ('0' <= c && c <= '9') - { - return c - '0'; - } - else if ('a' <= c && c <= 'z') - { - return c - 'a' + 10; - } - else - { - return c - 'A' + 10; - } - } - - /// - /// Unescapes a text string as escaped using . - /// Two-digit hex escapes (starting with "\x" are also recognised. - /// - public static string UnescapeText(string input) - { - return UnescapeBytes(input).ToStringUtf8(); - } - - /// - /// Like but escapes a text string. - /// The string is first encoded as UTF-8, then each byte escaped individually. - /// The returned value is guaranteed to be entirely ASCII. - /// - public static string EscapeText(string input) - { - return EscapeBytes(ByteString.CopyFromUtf8(input)); - } - - /// - /// Escapes bytes in the format used in protocol buffer text format, which - /// is the same as the format used for C string literals. All bytes - /// that are not printable 7-bit ASCII characters are escaped, as well as - /// backslash, single-quote, and double-quote characters. Characters for - /// which no defined short-hand escape sequence is defined will be escaped - /// using 3-digit octal sequences. - /// The returned value is guaranteed to be entirely ASCII. - /// - public static String EscapeBytes(ByteString input) - { - StringBuilder builder = new StringBuilder(input.Length); - foreach (byte b in input) - { - switch (b) - { - // C# does not use \a or \v - case 0x07: - builder.Append("\\a"); - break; - case (byte) '\b': - builder.Append("\\b"); - break; - case (byte) '\f': - builder.Append("\\f"); - break; - case (byte) '\n': - builder.Append("\\n"); - break; - case (byte) '\r': - builder.Append("\\r"); - break; - case (byte) '\t': - builder.Append("\\t"); - break; - case 0x0b: - builder.Append("\\v"); - break; - case (byte) '\\': - builder.Append("\\\\"); - break; - case (byte) '\'': - builder.Append("\\\'"); - break; - case (byte) '"': - builder.Append("\\\""); - break; - default: - if (b >= 0x20 && b < 128) - { - builder.Append((char) b); - } - else - { - builder.Append('\\'); - builder.Append((char) ('0' + ((b >> 6) & 3))); - builder.Append((char) ('0' + ((b >> 3) & 7))); - builder.Append((char) ('0' + (b & 7))); - } - break; - } - } - return builder.ToString(); - } - - /// - /// Performs string unescaping from C style (octal, hex, form feeds, tab etc) into a byte string. - /// - public static ByteString UnescapeBytes(string input) - { - byte[] result = new byte[input.Length]; - int pos = 0; - for (int i = 0; i < input.Length; i++) - { - char c = input[i]; - if (c > 127 || c < 32) - { - throw new FormatException("Escaped string must only contain ASCII"); - } - if (c != '\\') - { - result[pos++] = (byte) c; - continue; - } - if (i + 1 >= input.Length) - { - throw new FormatException("Invalid escape sequence: '\\' at end of string."); - } - - i++; - c = input[i]; - if (c >= '0' && c <= '7') - { - // Octal escape. - int code = ParseDigit(c); - if (i + 1 < input.Length && IsOctal(input[i + 1])) - { - i++; - code = code*8 + ParseDigit(input[i]); - } - if (i + 1 < input.Length && IsOctal(input[i + 1])) - { - i++; - code = code*8 + ParseDigit(input[i]); - } - result[pos++] = (byte) code; - } - else - { - switch (c) - { - case 'a': - result[pos++] = 0x07; - break; - case 'b': - result[pos++] = (byte) '\b'; - break; - case 'f': - result[pos++] = (byte) '\f'; - break; - case 'n': - result[pos++] = (byte) '\n'; - break; - case 'r': - result[pos++] = (byte) '\r'; - break; - case 't': - result[pos++] = (byte) '\t'; - break; - case 'v': - result[pos++] = 0x0b; - break; - case '\\': - result[pos++] = (byte) '\\'; - break; - case '\'': - result[pos++] = (byte) '\''; - break; - case '"': - result[pos++] = (byte) '\"'; - break; - - case 'x': - // hex escape - int code; - if (i + 1 < input.Length && IsHex(input[i + 1])) - { - i++; - code = ParseDigit(input[i]); - } - else - { - throw new FormatException("Invalid escape sequence: '\\x' with no digits"); - } - if (i + 1 < input.Length && IsHex(input[i + 1])) - { - ++i; - code = code*16 + ParseDigit(input[i]); - } - result[pos++] = (byte) code; - break; - - default: - throw new FormatException("Invalid escape sequence: '\\" + c + "'"); - } - } - } - - return ByteString.CopyFrom(result, 0, pos); - } - - public static void Merge(string text, IBuilder builder) - { - Merge(text, ExtensionRegistry.Empty, builder); - } - - public static void Merge(TextReader reader, IBuilder builder) - { - Merge(reader, ExtensionRegistry.Empty, builder); - } - - public static void Merge(TextReader reader, ExtensionRegistry registry, IBuilder builder) - { - Merge(reader.ReadToEnd(), registry, builder); - } - - public static void Merge(string text, ExtensionRegistry registry, IBuilder builder) - { - TextTokenizer tokenizer = new TextTokenizer(text); - - while (!tokenizer.AtEnd) - { - MergeField(tokenizer, registry, builder); - } - } - - /// - /// Parses a single field from the specified tokenizer and merges it into - /// the builder. - /// - private static void MergeField(TextTokenizer tokenizer, ExtensionRegistry extensionRegistry, - IBuilder builder) - { - FieldDescriptor field; - MessageDescriptor type = builder.DescriptorForType; - ExtensionInfo extension = null; - - if (tokenizer.TryConsume("[")) - { - // An extension. - StringBuilder name = new StringBuilder(tokenizer.ConsumeIdentifier()); - while (tokenizer.TryConsume(".")) - { - name.Append("."); - name.Append(tokenizer.ConsumeIdentifier()); - } - - extension = extensionRegistry.FindByName(type, name.ToString()); - - if (extension == null) - { - throw tokenizer.CreateFormatExceptionPreviousToken("Extension \"" + name + - "\" not found in the ExtensionRegistry."); - } - else if (extension.Descriptor.ContainingType != type) - { - throw tokenizer.CreateFormatExceptionPreviousToken("Extension \"" + name + - "\" does not extend message type \"" + - type.FullName + "\"."); - } - - tokenizer.Consume("]"); - - field = extension.Descriptor; - } - else - { - String name = tokenizer.ConsumeIdentifier(); - field = type.FindDescriptor(name); - - // Group names are expected to be capitalized as they appear in the - // .proto file, which actually matches their type names, not their field - // names. - if (field == null) - { - // Explicitly specify the invariant culture so that this code does not break when - // executing in Turkey. - String lowerName = name.ToLowerInvariant(); - field = type.FindDescriptor(lowerName); - // If the case-insensitive match worked but the field is NOT a group, - // TODO(jonskeet): What? Java comment ends here! - if (field != null && field.FieldType != FieldType.Group) - { - field = null; - } - } - // Again, special-case group names as described above. - if (field != null && field.FieldType == FieldType.Group && field.MessageType.Name != name) - { - field = null; - } - - if (field == null) - { - throw tokenizer.CreateFormatExceptionPreviousToken( - "Message type \"" + type.FullName + "\" has no field named \"" + name + "\"."); - } - } - - object value = null; - - if (field.MappedType == MappedType.Message) - { - tokenizer.TryConsume(":"); // optional - - String endToken; - if (tokenizer.TryConsume("<")) - { - endToken = ">"; - } - else - { - tokenizer.Consume("{"); - endToken = "}"; - } - - IBuilder subBuilder; - if (extension == null) - { - subBuilder = builder.CreateBuilderForField(field); - } - else - { - subBuilder = extension.DefaultInstance.WeakCreateBuilderForType() as IBuilder; - if (subBuilder == null) - { - throw new NotSupportedException("Lite messages are not supported."); - } - } - - while (!tokenizer.TryConsume(endToken)) - { - if (tokenizer.AtEnd) - { - throw tokenizer.CreateFormatException("Expected \"" + endToken + "\"."); - } - MergeField(tokenizer, extensionRegistry, subBuilder); - } - - value = subBuilder.WeakBuild(); - } - else - { - tokenizer.Consume(":"); - - switch (field.FieldType) - { - case FieldType.Int32: - case FieldType.SInt32: - case FieldType.SFixed32: - value = tokenizer.ConsumeInt32(); - break; - - case FieldType.Int64: - case FieldType.SInt64: - case FieldType.SFixed64: - value = tokenizer.ConsumeInt64(); - break; - - case FieldType.UInt32: - case FieldType.Fixed32: - value = tokenizer.ConsumeUInt32(); - break; - - case FieldType.UInt64: - case FieldType.Fixed64: - value = tokenizer.ConsumeUInt64(); - break; - - case FieldType.Float: - value = tokenizer.ConsumeFloat(); - break; - - case FieldType.Double: - value = tokenizer.ConsumeDouble(); - break; - - case FieldType.Bool: - value = tokenizer.ConsumeBoolean(); - break; - - case FieldType.String: - value = tokenizer.ConsumeString(); - break; - - case FieldType.Bytes: - value = tokenizer.ConsumeByteString(); - break; - - case FieldType.Enum: - { - EnumDescriptor enumType = field.EnumType; - - if (tokenizer.LookingAtInteger()) - { - int number = tokenizer.ConsumeInt32(); - value = enumType.FindValueByNumber(number); - if (value == null) - { - throw tokenizer.CreateFormatExceptionPreviousToken( - "Enum type \"" + enumType.FullName + - "\" has no value with number " + number + "."); - } - } - else - { - String id = tokenizer.ConsumeIdentifier(); - value = enumType.FindValueByName(id); - if (value == null) - { - throw tokenizer.CreateFormatExceptionPreviousToken( - "Enum type \"" + enumType.FullName + - "\" has no value named \"" + id + "\"."); - } - } - - break; - } - - case FieldType.Message: - case FieldType.Group: - throw new InvalidOperationException("Can't get here."); - } - } - - if (field.IsRepeated) - { - builder.WeakAddRepeatedField(field, value); - } - else - { - builder.SetField(field, value); - } - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers/TextGenerator.cs b/csharp/src/ProtocolBuffers/TextGenerator.cs index 30cbf0fd..80910ba1 100644 --- a/csharp/src/ProtocolBuffers/TextGenerator.cs +++ b/csharp/src/ProtocolBuffers/TextGenerator.cs @@ -38,7 +38,7 @@ using System; using System.IO; using System.Text; -namespace Google.ProtocolBuffers +namespace Google.Protobuf { /// /// Helper class to control indentation. Used for TextFormat and by ProtoGen. diff --git a/csharp/src/ProtocolBuffers/TextTokenizer.cs b/csharp/src/ProtocolBuffers/TextTokenizer.cs deleted file mode 100644 index 5bb27fd0..00000000 --- a/csharp/src/ProtocolBuffers/TextTokenizer.cs +++ /dev/null @@ -1,501 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Globalization; -using System.Text.RegularExpressions; - -namespace Google.ProtocolBuffers -{ - /// - /// Represents a stream of tokens parsed from a string. - /// - internal sealed class TextTokenizer - { - private readonly string text; - private string currentToken; - - /// - /// The character index within the text to perform the next regex match at. - /// - private int matchPos = 0; - - /// - /// The character index within the text at which the current token begins. - /// - private int pos = 0; - - /// - /// The line number of the current token. - /// - private int line = 0; - - /// - /// The column number of the current token. - /// - private int column = 0; - - /// - /// The line number of the previous token. - /// - private int previousLine = 0; - - /// - /// The column number of the previous token. - /// - private int previousColumn = 0; - - // Note: atomic groups used to mimic possessive quantifiers in Java in both of these regexes - internal static readonly Regex WhitespaceAndCommentPattern = new Regex("\\G(?>(\\s|(#.*$))+)", - FrameworkPortability. - CompiledRegexWhereAvailable | - RegexOptions.Multiline); - - private static readonly Regex TokenPattern = new Regex( - "\\G[a-zA-Z_](?>[0-9a-zA-Z_+-]*)|" + // an identifier - "\\G[0-9+-](?>[0-9a-zA-Z_.+-]*)|" + // a number - "\\G\"(?>([^\"\\\n\\\\]|\\\\.)*)(\"|\\\\?$)|" + // a double-quoted string - "\\G\'(?>([^\"\\\n\\\\]|\\\\.)*)(\'|\\\\?$)", // a single-quoted string - FrameworkPortability.CompiledRegexWhereAvailable | RegexOptions.Multiline); - - private static readonly Regex DoubleInfinity = new Regex("^-?inf(inity)?$", - FrameworkPortability.CompiledRegexWhereAvailable | - RegexOptions.IgnoreCase); - - private static readonly Regex FloatInfinity = new Regex("^-?inf(inity)?f?$", - FrameworkPortability.CompiledRegexWhereAvailable | - RegexOptions.IgnoreCase); - - private static readonly Regex FloatNan = new Regex("^nanf?$", - FrameworkPortability.CompiledRegexWhereAvailable | - RegexOptions.IgnoreCase); - - /** Construct a tokenizer that parses tokens from the given text. */ - - public TextTokenizer(string text) - { - this.text = text; - SkipWhitespace(); - NextToken(); - } - - /// - /// Are we at the end of the input? - /// - public bool AtEnd - { - get { return currentToken.Length == 0; } - } - - /// - /// Advances to the next token. - /// - public void NextToken() - { - previousLine = line; - previousColumn = column; - - // Advance the line counter to the current position. - while (pos < matchPos) - { - if (text[pos] == '\n') - { - ++line; - column = 0; - } - else - { - ++column; - } - ++pos; - } - - // Match the next token. - if (matchPos == text.Length) - { - // EOF - currentToken = ""; - } - else - { - Match match = TokenPattern.Match(text, matchPos); - if (match.Success) - { - currentToken = match.Value; - matchPos += match.Length; - } - else - { - // Take one character. - currentToken = text[matchPos].ToString(); - matchPos++; - } - - SkipWhitespace(); - } - } - - /// - /// Skip over any whitespace so that matchPos starts at the next token. - /// - private void SkipWhitespace() - { - Match match = WhitespaceAndCommentPattern.Match(text, matchPos); - if (match.Success) - { - matchPos += match.Length; - } - } - - /// - /// If the next token exactly matches the given token, consume it and return - /// true. Otherwise, return false without doing anything. - /// - public bool TryConsume(string token) - { - if (currentToken == token) - { - NextToken(); - return true; - } - return false; - } - - /* - * If the next token exactly matches {@code token}, consume it. Otherwise, - * throw a {@link ParseException}. - */ - - /// - /// If the next token exactly matches the specified one, consume it. - /// Otherwise, throw a FormatException. - /// - /// - public void Consume(string token) - { - if (!TryConsume(token)) - { - throw CreateFormatException("Expected \"" + token + "\"."); - } - } - - /// - /// Returns true if the next token is an integer, but does not consume it. - /// - public bool LookingAtInteger() - { - if (currentToken.Length == 0) - { - return false; - } - - char c = currentToken[0]; - return ('0' <= c && c <= '9') || c == '-' || c == '+'; - } - - /// - /// If the next token is an identifier, consume it and return its value. - /// Otherwise, throw a FormatException. - /// - public string ConsumeIdentifier() - { - foreach (char c in currentToken) - { - if (('a' <= c && c <= 'z') || - ('A' <= c && c <= 'Z') || - ('0' <= c && c <= '9') || - (c == '_') || (c == '.')) - { - // OK - } - else - { - throw CreateFormatException("Expected identifier."); - } - } - - string result = currentToken; - NextToken(); - return result; - } - - /// - /// If the next token is a 32-bit signed integer, consume it and return its - /// value. Otherwise, throw a FormatException. - /// - public int ConsumeInt32() - { - try - { - int result = TextFormat.ParseInt32(currentToken); - NextToken(); - return result; - } - catch (FormatException e) - { - throw CreateIntegerParseException(e); - } - } - - /// - /// If the next token is a 32-bit unsigned integer, consume it and return its - /// value. Otherwise, throw a FormatException. - /// - public uint ConsumeUInt32() - { - try - { - uint result = TextFormat.ParseUInt32(currentToken); - NextToken(); - return result; - } - catch (FormatException e) - { - throw CreateIntegerParseException(e); - } - } - - /// - /// If the next token is a 64-bit signed integer, consume it and return its - /// value. Otherwise, throw a FormatException. - /// - public long ConsumeInt64() - { - try - { - long result = TextFormat.ParseInt64(currentToken); - NextToken(); - return result; - } - catch (FormatException e) - { - throw CreateIntegerParseException(e); - } - } - - /// - /// If the next token is a 64-bit unsigned integer, consume it and return its - /// value. Otherwise, throw a FormatException. - /// - public ulong ConsumeUInt64() - { - try - { - ulong result = TextFormat.ParseUInt64(currentToken); - NextToken(); - return result; - } - catch (FormatException e) - { - throw CreateIntegerParseException(e); - } - } - - /// - /// If the next token is a double, consume it and return its value. - /// Otherwise, throw a FormatException. - /// - public double ConsumeDouble() - { - // We need to parse infinity and nan separately because - // double.Parse() does not accept "inf", "infinity", or "nan". - if (DoubleInfinity.IsMatch(currentToken)) - { - bool negative = currentToken.StartsWith("-"); - NextToken(); - return negative ? double.NegativeInfinity : double.PositiveInfinity; - } - if (currentToken.Equals("nan", StringComparison.OrdinalIgnoreCase)) - { - NextToken(); - return Double.NaN; - } - - try - { - double result = double.Parse(currentToken, FrameworkPortability.InvariantCulture); - NextToken(); - return result; - } - catch (FormatException e) - { - throw CreateFloatParseException(e); - } - catch (OverflowException e) - { - throw CreateFloatParseException(e); - } - } - - /// - /// If the next token is a float, consume it and return its value. - /// Otherwise, throw a FormatException. - /// - public float ConsumeFloat() - { - // We need to parse infinity and nan separately because - // Float.parseFloat() does not accept "inf", "infinity", or "nan". - if (FloatInfinity.IsMatch(currentToken)) - { - bool negative = currentToken.StartsWith("-"); - NextToken(); - return negative ? float.NegativeInfinity : float.PositiveInfinity; - } - if (FloatNan.IsMatch(currentToken)) - { - NextToken(); - return float.NaN; - } - - if (currentToken.EndsWith("f")) - { - currentToken = currentToken.TrimEnd('f'); - } - - try - { - float result = float.Parse(currentToken, FrameworkPortability.InvariantCulture); - NextToken(); - return result; - } - catch (FormatException e) - { - throw CreateFloatParseException(e); - } - catch (OverflowException e) - { - throw CreateFloatParseException(e); - } - } - - /// - /// If the next token is a Boolean, consume it and return its value. - /// Otherwise, throw a FormatException. - /// - public bool ConsumeBoolean() - { - if (currentToken == "true") - { - NextToken(); - return true; - } - if (currentToken == "false") - { - NextToken(); - return false; - } - throw CreateFormatException("Expected \"true\" or \"false\"."); - } - - /// - /// If the next token is a string, consume it and return its (unescaped) value. - /// Otherwise, throw a FormatException. - /// - public string ConsumeString() - { - return ConsumeByteString().ToStringUtf8(); - } - - /// - /// If the next token is a string, consume it, unescape it as a - /// ByteString and return it. Otherwise, throw a FormatException. - /// - public ByteString ConsumeByteString() - { - char quote = currentToken.Length > 0 ? currentToken[0] : '\0'; - if (quote != '\"' && quote != '\'') - { - throw CreateFormatException("Expected string."); - } - - if (currentToken.Length < 2 || - currentToken[currentToken.Length - 1] != quote) - { - throw CreateFormatException("String missing ending quote."); - } - - try - { - string escaped = currentToken.Substring(1, currentToken.Length - 2); - ByteString result = TextFormat.UnescapeBytes(escaped); - NextToken(); - return result; - } - catch (FormatException e) - { - throw CreateFormatException(e.Message); - } - } - - /// - /// Returns a format exception with the current line and column numbers - /// in the description, suitable for throwing. - /// - public FormatException CreateFormatException(string description) - { - // Note: People generally prefer one-based line and column numbers. - return new FormatException((line + 1) + ":" + (column + 1) + ": " + description); - } - - /// - /// Returns a format exception with the line and column numbers of the - /// previous token in the description, suitable for throwing. - /// - public FormatException CreateFormatExceptionPreviousToken(string description) - { - // Note: People generally prefer one-based line and column numbers. - return new FormatException((previousLine + 1) + ":" + (previousColumn + 1) + ": " + description); - } - - /// - /// Constructs an appropriate FormatException for the given existing exception - /// when trying to parse an integer. - /// - private FormatException CreateIntegerParseException(FormatException e) - { - return CreateFormatException("Couldn't parse integer: " + e.Message); - } - - /// - /// Constructs an appropriate FormatException for the given existing exception - /// when trying to parse a float or double. - /// - private FormatException CreateFloatParseException(Exception e) - { - return CreateFormatException("Couldn't parse number: " + e.Message); - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers/ThrowHelper.cs b/csharp/src/ProtocolBuffers/ThrowHelper.cs index 69e5f569..097b5032 100644 --- a/csharp/src/ProtocolBuffers/ThrowHelper.cs +++ b/csharp/src/ProtocolBuffers/ThrowHelper.cs @@ -37,7 +37,7 @@ using System; using System.Collections.Generic; -namespace Google.ProtocolBuffers +namespace Google.Protobuf { /// /// Helper methods for throwing exceptions diff --git a/csharp/src/ProtocolBuffers/UninitializedMessageException.cs b/csharp/src/ProtocolBuffers/UninitializedMessageException.cs deleted file mode 100644 index 9e4f856e..00000000 --- a/csharp/src/ProtocolBuffers/UninitializedMessageException.cs +++ /dev/null @@ -1,208 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Text; - -#if !LITE -using Google.ProtocolBuffers.Collections; -using Google.ProtocolBuffers.Descriptors; - -#endif - -namespace Google.ProtocolBuffers -{ - /// - /// TODO(jonskeet): Write summary text. - /// - public sealed class UninitializedMessageException : Exception - { - private readonly IList missingFields; - - private UninitializedMessageException(IList missingFields) - : base(BuildDescription(missingFields)) - { - this.missingFields = new List(missingFields); - } - - /// - /// Returns a read-only list of human-readable names of - /// required fields missing from this message. Each name - /// is a full path to a field, e.g. "foo.bar[5].baz" - /// - public IList MissingFields - { - get { return missingFields; } - } - - /// - /// Converts this exception into an InvalidProtocolBufferException. - /// When a parsed message is missing required fields, this should be thrown - /// instead of UninitializedMessageException. - /// - public InvalidProtocolBufferException AsInvalidProtocolBufferException() - { - return new InvalidProtocolBufferException(Message); - } - - /// - /// Constructs the description string for a given list of missing fields. - /// - private static string BuildDescription(IEnumerable missingFields) - { - StringBuilder description = new StringBuilder("Message missing required fields: "); - bool first = true; - foreach (string field in missingFields) - { - if (first) - { - first = false; - } - else - { - description.Append(", "); - } - description.Append(field); - } - return description.ToString(); - } - - /// - /// For Lite exceptions that do not known how to enumerate missing fields - /// - public UninitializedMessageException(IMessageLite message) - : base(String.Format("Message {0} is missing required fields", message.GetType())) - { - missingFields = new List(); - } - -#if !LITE - public UninitializedMessageException(IMessage message) - : this(FindMissingFields(message)) - { - } - - /// - /// Returns a list of the full "paths" of missing required - /// fields in the specified message. - /// - private static IList FindMissingFields(IMessage message) - { - List results = new List(); - FindMissingFields(message, "", results); - return results; - } - - /// - /// Recursive helper implementing FindMissingFields. - /// - private static void FindMissingFields(IMessage message, String prefix, List results) - { - foreach (FieldDescriptor field in message.DescriptorForType.Fields) - { - if (field.IsRequired && !message.HasField(field)) - { - results.Add(prefix + field.Name); - } - } - - foreach (KeyValuePair entry in message.AllFields) - { - FieldDescriptor field = entry.Key; - object value = entry.Value; - - if (field.MappedType == MappedType.Message) - { - if (field.IsRepeated) - { - int i = 0; - foreach (object element in (IEnumerable) value) - { - if (element is IMessage) - { - FindMissingFields((IMessage) element, SubMessagePrefix(prefix, field, i++), results); - } - else - { - results.Add(prefix + field.Name); - } - } - } - else - { - if (message.HasField(field)) - { - if (value is IMessage) - { - FindMissingFields((IMessage) value, SubMessagePrefix(prefix, field, -1), results); - } - else - { - results.Add(prefix + field.Name); - } - } - } - } - } - } - - private static String SubMessagePrefix(String prefix, FieldDescriptor field, int index) - { - StringBuilder result = new StringBuilder(prefix); - if (field.IsExtension) - { - result.Append('(') - .Append(field.FullName) - .Append(')'); - } - else - { - result.Append(field.Name); - } - if (index != -1) - { - result.Append('[') - .Append(index) - .Append(']'); - } - result.Append('.'); - return result.ToString(); - } -#endif - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers/UnknownField.cs b/csharp/src/ProtocolBuffers/UnknownField.cs deleted file mode 100644 index 7650b9df..00000000 --- a/csharp/src/ProtocolBuffers/UnknownField.cs +++ /dev/null @@ -1,415 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using Google.ProtocolBuffers.Collections; - -namespace Google.ProtocolBuffers -{ - /// - /// Represents a single field in an UnknownFieldSet. - /// - /// An UnknownField consists of five lists of values. The lists correspond - /// to the five "wire types" used in the protocol buffer binary format. - /// The wire type of each field can be determined from the encoded form alone, - /// without knowing the field's declared type. So, we are able to parse - /// unknown values at least this far and separate them. Normally, only one - /// of the five lists will contain any values, since it is impossible to - /// define a valid message type that declares two different types for the - /// same field number. However, the code is designed to allow for the case - /// where the same unknown field number is encountered using multiple different - /// wire types. - /// - /// UnknownField is an immutable class. To construct one, you must use an - /// UnknownField.Builder. - /// - public sealed class UnknownField - { - public const string UnknownFieldName = "unknown_field"; - private static readonly UnknownField defaultInstance = CreateBuilder().Build(); - private readonly ReadOnlyCollection varintList; - private readonly ReadOnlyCollection fixed32List; - private readonly ReadOnlyCollection fixed64List; - private readonly ReadOnlyCollection lengthDelimitedList; - private readonly ReadOnlyCollection groupList; - - private UnknownField(ReadOnlyCollection varintList, - ReadOnlyCollection fixed32List, - ReadOnlyCollection fixed64List, - ReadOnlyCollection lengthDelimitedList, - ReadOnlyCollection groupList) - { - this.varintList = varintList; - this.fixed32List = fixed32List; - this.fixed64List = fixed64List; - this.lengthDelimitedList = lengthDelimitedList; - this.groupList = groupList; - } - - public static UnknownField DefaultInstance - { - get { return defaultInstance; } - } - - /// - /// The list of varint values for this field. - /// - public IList VarintList - { - get { return varintList; } - } - - /// - /// The list of fixed32 values for this field. - /// - public IList Fixed32List - { - get { return fixed32List; } - } - - /// - /// The list of fixed64 values for this field. - /// - public IList Fixed64List - { - get { return fixed64List; } - } - - /// - /// The list of length-delimited values for this field. - /// - public IList LengthDelimitedList - { - get { return lengthDelimitedList; } - } - - /// - /// The list of embedded group values for this field. These - /// are represented using UnknownFieldSets rather than Messages - /// since the group's type is presumably unknown. - /// - public IList GroupList - { - get { return groupList; } - } - - public override bool Equals(object other) - { - if (ReferenceEquals(this, other)) - { - return true; - } - UnknownField otherField = other as UnknownField; - return otherField != null - && Lists.Equals(varintList, otherField.varintList) - && Lists.Equals(fixed32List, otherField.fixed32List) - && Lists.Equals(fixed64List, otherField.fixed64List) - && Lists.Equals(lengthDelimitedList, otherField.lengthDelimitedList) - && Lists.Equals(groupList, otherField.groupList); - } - - public override int GetHashCode() - { - int hash = 43; - hash = hash*47 + Lists.GetHashCode(varintList); - hash = hash*47 + Lists.GetHashCode(fixed32List); - hash = hash*47 + Lists.GetHashCode(fixed64List); - hash = hash*47 + Lists.GetHashCode(lengthDelimitedList); - hash = hash*47 + Lists.GetHashCode(groupList); - return hash; - } - - /// - /// Constructs a new Builder. - /// - public static Builder CreateBuilder() - { - return new Builder(); - } - - /// - /// Constructs a new Builder and initializes it to a copy of . - /// - public static Builder CreateBuilder(UnknownField copyFrom) - { - return new Builder().MergeFrom(copyFrom); - } - - /// - /// Serializes the field, including the field number, and writes it to - /// . - /// - public void WriteTo(int fieldNumber, ICodedOutputStream output) - { - foreach (ulong value in varintList) - { - output.WriteUnknownField(fieldNumber, WireFormat.WireType.Varint, value); - } - foreach (uint value in fixed32List) - { - output.WriteUnknownField(fieldNumber, WireFormat.WireType.Fixed32, value); - } - foreach (ulong value in fixed64List) - { - output.WriteUnknownField(fieldNumber, WireFormat.WireType.Fixed64, value); - } - foreach (ByteString value in lengthDelimitedList) - { - output.WriteUnknownBytes(fieldNumber, value); - } - foreach (UnknownFieldSet value in groupList) - { -#pragma warning disable 0612 - output.WriteUnknownGroup(fieldNumber, value); -#pragma warning restore 0612 - } - } - - /// - /// Computes the number of bytes required to encode this field, including field - /// number. - /// - public int GetSerializedSize(int fieldNumber) - { - int result = 0; - foreach (ulong value in varintList) - { - result += CodedOutputStream.ComputeUInt64Size(fieldNumber, value); - } - foreach (uint value in fixed32List) - { - result += CodedOutputStream.ComputeFixed32Size(fieldNumber, value); - } - foreach (ulong value in fixed64List) - { - result += CodedOutputStream.ComputeFixed64Size(fieldNumber, value); - } - foreach (ByteString value in lengthDelimitedList) - { - result += CodedOutputStream.ComputeBytesSize(fieldNumber, value); - } - foreach (UnknownFieldSet value in groupList) - { -#pragma warning disable 0612 - result += CodedOutputStream.ComputeUnknownGroupSize(fieldNumber, value); -#pragma warning restore 0612 - } - return result; - } - - /// - /// Serializes the length-delimited values of the field, including field - /// number, and writes them to using the MessageSet wire format. - /// - /// - /// - public void WriteAsMessageSetExtensionTo(int fieldNumber, ICodedOutputStream output) - { - foreach (ByteString value in lengthDelimitedList) - { - output.WriteMessageSetExtension(fieldNumber, UnknownFieldName, value); - } - } - - /// - /// Get the number of bytes required to encode this field, incuding field number, - /// using the MessageSet wire format. - /// - public int GetSerializedSizeAsMessageSetExtension(int fieldNumber) - { - int result = 0; - foreach (ByteString value in lengthDelimitedList) - { - result += CodedOutputStream.ComputeRawMessageSetExtensionSize(fieldNumber, value); - } - return result; - } - - /// - /// Used to build instances of UnknownField. - /// - public sealed class Builder - { - private List varintList; - private List fixed32List; - private List fixed64List; - private List lengthDelimitedList; - private List groupList; - - /// - /// Builds the field. After building, the builder is reset to an empty - /// state. (This is actually easier than making it unusable.) - /// - public UnknownField Build() - { - return new UnknownField(MakeReadOnly(ref varintList), - MakeReadOnly(ref fixed32List), - MakeReadOnly(ref fixed64List), - MakeReadOnly(ref lengthDelimitedList), - MakeReadOnly(ref groupList)); - } - - /// - /// Merge the values in into this field. For each list - /// of values, 's values are append to the ones in this - /// field. - /// - public Builder MergeFrom(UnknownField other) - { - varintList = AddAll(varintList, other.VarintList); - fixed32List = AddAll(fixed32List, other.Fixed32List); - fixed64List = AddAll(fixed64List, other.Fixed64List); - lengthDelimitedList = AddAll(lengthDelimitedList, other.LengthDelimitedList); - groupList = AddAll(groupList, other.GroupList); - return this; - } - - /// - /// Returns a new list containing all of the given specified values from - /// both the and lists. - /// If is null and is empty, - /// null is returned. Otherwise, either a new list is created (if - /// is null) or the elements of are added to . - /// - private static List AddAll(List current, IList extras) - { - if (extras.Count == 0) - { - return current; - } - if (current == null) - { - current = new List(extras); - } - else - { - current.AddRange(extras); - } - return current; - } - - /// - /// Clears the contents of this builder. - /// - public Builder Clear() - { - varintList = null; - fixed32List = null; - fixed64List = null; - lengthDelimitedList = null; - groupList = null; - return this; - } - - /// - /// Adds a varint value. - /// - public Builder AddVarint(ulong value) - { - varintList = Add(varintList, value); - return this; - } - - /// - /// Adds a fixed32 value. - /// - public Builder AddFixed32(uint value) - { - fixed32List = Add(fixed32List, value); - return this; - } - - /// - /// Adds a fixed64 value. - /// - public Builder AddFixed64(ulong value) - { - fixed64List = Add(fixed64List, value); - return this; - } - - /// - /// Adds a length-delimited value. - /// - public Builder AddLengthDelimited(ByteString value) - { - lengthDelimitedList = Add(lengthDelimitedList, value); - return this; - } - - /// - /// Adds an embedded group. - /// - /// - /// - public Builder AddGroup(UnknownFieldSet value) - { - groupList = Add(groupList, value); - return this; - } - - /// - /// Adds to the , creating - /// a new list if is null. The list is returned - either - /// the original reference or the new list. - /// - private static List Add(List list, T value) - { - if (list == null) - { - list = new List(); - } - list.Add(value); - return list; - } - - /// - /// Returns a read-only version of the given IList, and clears - /// the field used for . If the value - /// is null, an empty list is produced using Lists.Empty. - /// - /// - private static ReadOnlyCollection MakeReadOnly(ref List list) - { - ReadOnlyCollection ret = list == null ? Lists.Empty : new ReadOnlyCollection(list); - list = null; - return ret; - } - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers/UnknownFieldSet.cs b/csharp/src/ProtocolBuffers/UnknownFieldSet.cs deleted file mode 100644 index d5d0675d..00000000 --- a/csharp/src/ProtocolBuffers/UnknownFieldSet.cs +++ /dev/null @@ -1,1061 +0,0 @@ -#region Copyright notice and license - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// http://github.com/jskeet/dotnet-protobufs/ -// Original C++/Java/Python code: -// http://code.google.com/p/protobuf/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -#endregion - -using System; -using System.Collections.Generic; -using System.IO; -using Google.ProtocolBuffers.Collections; -using Google.ProtocolBuffers.Descriptors; - -namespace Google.ProtocolBuffers -{ - /// - /// Used to keep track of fields which were seen when parsing a protocol message - /// but whose field numbers or types are unrecognized. This most frequently - /// occurs when new fields are added to a message type and then messages containing - /// those fields are read by old software that was built before the new types were - /// added. - /// - /// Every message contains an UnknownFieldSet. - /// - /// Most users will never need to use this class directly. - /// - public sealed partial class UnknownFieldSet : IMessageLite - { - private static readonly UnknownFieldSet defaultInstance = - new UnknownFieldSet(new Dictionary()); - - private readonly IDictionary fields; - - private UnknownFieldSet(IDictionary fields) - { - this.fields = fields; - } - - /// - /// Creates a new unknown field set builder. - /// - public static Builder CreateBuilder() - { - return new Builder(); - } - - /// - /// Creates a new unknown field set builder - /// and initialize it from . - /// - public static Builder CreateBuilder(UnknownFieldSet original) - { - return new Builder().MergeFrom(original); - } - - public static UnknownFieldSet DefaultInstance - { - get { return defaultInstance; } - } - - /// - /// Returns a read-only view of the mapping from field numbers to values. - /// - public IDictionary FieldDictionary - { - get { return Dictionaries.AsReadOnly(fields); } - } - - /// - /// Checks whether or not the given field number is present in the set. - /// - public bool HasField(int field) - { - return fields.ContainsKey(field); - } - - /// - /// Fetches a field by number, returning an empty field if not present. - /// Never returns null. - /// - public UnknownField this[int number] - { - get - { - UnknownField ret; - if (!fields.TryGetValue(number, out ret)) - { - ret = UnknownField.DefaultInstance; - } - return ret; - } - } - - /// - /// Serializes the set and writes it to . - /// - public void WriteTo(ICodedOutputStream output) - { - // Avoid creating enumerator for the most common code path. - if (fields.Count > 0) - { - foreach (KeyValuePair entry in fields) - { - entry.Value.WriteTo(entry.Key, output); - } - } - } - - /// - /// Gets the number of bytes required to encode this set. - /// - public int SerializedSize - { - get - { - // Avoid creating enumerator for the most common code path. - if (fields.Count == 0) - { - return 0; - } - - int result = 0; - foreach (KeyValuePair entry in fields) - { - result += entry.Value.GetSerializedSize(entry.Key); - } - return result; - } - } - - /// - /// Converts the set to a string in protocol buffer text format. This - /// is just a trivial wrapper around TextFormat.PrintToString. - /// - public override String ToString() - { - return TextFormat.PrintToString(this); - } - - /// - /// Converts the set to a string in protocol buffer text format. This - /// is just a trivial wrapper around TextFormat.PrintToString. - /// - public void PrintTo(TextWriter writer) - { - TextFormat.Print(this, writer); - } - - /// - /// Serializes the message to a ByteString and returns it. This is - /// just a trivial wrapper around WriteTo(ICodedOutputStream). - /// - /// - public ByteString ToByteString() - { - ByteString.CodedBuilder codedBuilder = new ByteString.CodedBuilder(SerializedSize); - WriteTo(codedBuilder.CodedOutput); - return codedBuilder.Build(); - } - - /// - /// Serializes the message to a byte array and returns it. This is - /// just a trivial wrapper around WriteTo(ICodedOutputStream). - /// - /// - public byte[] ToByteArray() - { - byte[] data = new byte[SerializedSize]; - CodedOutputStream output = CodedOutputStream.CreateInstance(data); - WriteTo(output); - output.CheckNoSpaceLeft(); - return data; - } - - /// - /// Serializes the message and writes it to . This is - /// just a trivial wrapper around WriteTo(ICodedOutputStream). - /// - /// - public void WriteTo(Stream output) - { - CodedOutputStream codedOutput = CodedOutputStream.CreateInstance(output); - WriteTo(codedOutput); - codedOutput.Flush(); - } - - /// - /// Serializes the set and writes it to using - /// the MessageSet wire format. - /// - public void WriteAsMessageSetTo(ICodedOutputStream output) - { - // Avoid creating enumerator for the most common code path. - if (fields.Count > 0) - { - foreach (KeyValuePair entry in fields) - { - entry.Value.WriteAsMessageSetExtensionTo(entry.Key, output); - } - } - } - - /// - /// Gets the number of bytes required to encode this set using the MessageSet - /// wire format. - /// - public int SerializedSizeAsMessageSet - { - get - { - // Avoid creating enumerator for the most common code path. - if (fields.Count == 0) - { - return 0; - } - - int result = 0; - foreach (KeyValuePair entry in fields) - { - result += entry.Value.GetSerializedSizeAsMessageSetExtension(entry.Key); - } - return result; - } - } - - public override bool Equals(object other) - { - if (ReferenceEquals(this, other)) - { - return true; - } - UnknownFieldSet otherSet = other as UnknownFieldSet; - return otherSet != null && Dictionaries.Equals(fields, otherSet.fields); - } - - public override int GetHashCode() - { - return Dictionaries.GetHashCode(fields); - } - - /// - /// Parses an UnknownFieldSet from the given input. - /// - public static UnknownFieldSet ParseFrom(ICodedInputStream input) - { - return CreateBuilder().MergeFrom(input).Build(); - } - - /// - /// Parses an UnknownFieldSet from the given data. - /// - public static UnknownFieldSet ParseFrom(ByteString data) - { - return CreateBuilder().MergeFrom(data).Build(); - } - - /// - /// Parses an UnknownFieldSet from the given data. - /// - public static UnknownFieldSet ParseFrom(byte[] data) - { - return CreateBuilder().MergeFrom(data).Build(); - } - - /// - /// Parses an UnknownFieldSet from the given input. - /// - public static UnknownFieldSet ParseFrom(Stream input) - { - return CreateBuilder().MergeFrom(input).Build(); - } - - #region IMessageLite Members - - public bool IsInitialized - { - get { return fields != null; } - } - - public void WriteDelimitedTo(Stream output) - { - CodedOutputStream codedOutput = CodedOutputStream.CreateInstance(output); - codedOutput.WriteRawVarint32((uint) SerializedSize); - WriteTo(codedOutput); - codedOutput.Flush(); - } - - public IBuilderLite WeakCreateBuilderForType() - { - return new Builder(); - } - - public IBuilderLite WeakToBuilder() - { - return new Builder(fields); - } - - public IMessageLite WeakDefaultInstanceForType - { - get { return defaultInstance; } - } - - #endregion - - /// - /// Builder for UnknownFieldSets. - /// - public sealed partial class Builder : IBuilderLite - { - /// - /// Mapping from number to field. Note that by using a SortedList we ensure - /// that the fields will be serialized in ascending order. - /// - private IDictionary fields; - - // Optimization: We keep around a builder for the last field that was - // modified so that we can efficiently add to it multiple times in a - // row (important when parsing an unknown repeated field). - private int lastFieldNumber; - private UnknownField.Builder lastField; - - internal Builder() - { - fields = new SortedDictionary(); - } - - internal Builder(IDictionary dictionary) - { - fields = new SortedDictionary(dictionary); - } - - /// - /// Returns a field builder for the specified field number, including any values - /// which already exist. - /// - private UnknownField.Builder GetFieldBuilder(int number) - { - if (lastField != null) - { - if (number == lastFieldNumber) - { - return lastField; - } - // Note: AddField() will reset lastField and lastFieldNumber. - AddField(lastFieldNumber, lastField.Build()); - } - if (number == 0) - { - return null; - } - - lastField = UnknownField.CreateBuilder(); - UnknownField existing; - if (fields.TryGetValue(number, out existing)) - { - lastField.MergeFrom(existing); - } - lastFieldNumber = number; - return lastField; - } - - /// - /// Build the UnknownFieldSet and return it. Once this method has been called, - /// this instance will no longer be usable. Calling any method after this - /// will throw a NullReferenceException. - /// - public UnknownFieldSet Build() - { - GetFieldBuilder(0); // Force lastField to be built. - UnknownFieldSet result = fields.Count == 0 ? DefaultInstance : new UnknownFieldSet(fields); - fields = null; - return result; - } - - /// - /// Adds a field to the set. If a field with the same number already exists, it - /// is replaced. - /// - public Builder AddField(int number, UnknownField field) - { - if (number == 0) - { - throw new ArgumentOutOfRangeException("number", "Zero is not a valid field number."); - } - if (lastField != null && lastFieldNumber == number) - { - // Discard this. - lastField = null; - lastFieldNumber = 0; - } - fields[number] = field; - return this; - } - - /// - /// Resets the builder to an empty set. - /// - public Builder Clear() - { - fields.Clear(); - lastFieldNumber = 0; - lastField = null; - return this; - } - - /// - /// Parse an entire message from and merge - /// its fields into this set. - /// - public Builder MergeFrom(ICodedInputStream input) - { - uint tag; - string name; - while (input.ReadTag(out tag, out name)) - { - if (tag == 0) - { - if (input.SkipField()) - { - continue; //can't merge unknown without field tag - } - break; - } - - if (!MergeFieldFrom(tag, input)) - { - break; - } - } - return this; - } - - /// - /// Parse a single field from and merge it - /// into this set. - /// - /// The field's tag number, which was already parsed. - /// The coded input stream containing the field - /// false if the tag is an "end group" tag, true otherwise - public bool MergeFieldFrom(uint tag, ICodedInputStream input) - { - if (tag == 0) - { - input.SkipField(); - return true; - } - - int number = WireFormat.GetTagFieldNumber(tag); - switch (WireFormat.GetTagWireType(tag)) - { - case WireFormat.WireType.Varint: - { - ulong uint64 = 0; - if (input.ReadUInt64(ref uint64)) - { - GetFieldBuilder(number).AddVarint(uint64); - } - return true; - } - case WireFormat.WireType.Fixed32: - { - uint uint32 = 0; - if (input.ReadFixed32(ref uint32)) - { - GetFieldBuilder(number).AddFixed32(uint32); - } - return true; - } - case WireFormat.WireType.Fixed64: - { - ulong uint64 = 0; - if (input.ReadFixed64(ref uint64)) - { - GetFieldBuilder(number).AddFixed64(uint64); - } - return true; - } - case WireFormat.WireType.LengthDelimited: - { - ByteString bytes = null; - if (input.ReadBytes(ref bytes)) - { - GetFieldBuilder(number).AddLengthDelimited(bytes); - } - return true; - } - case WireFormat.WireType.StartGroup: - { - Builder subBuilder = CreateBuilder(); -#pragma warning disable 0612 - input.ReadUnknownGroup(number, subBuilder); -#pragma warning restore 0612 - GetFieldBuilder(number).AddGroup(subBuilder.Build()); - return true; - } - case WireFormat.WireType.EndGroup: - return false; - default: - throw InvalidProtocolBufferException.InvalidWireType(); - } - } - - /// - /// Parses as an UnknownFieldSet and merge it - /// with the set being built. This is just a small wrapper around - /// MergeFrom(ICodedInputStream). - /// - public Builder MergeFrom(Stream input) - { - CodedInputStream codedInput = CodedInputStream.CreateInstance(input); - MergeFrom(codedInput); - codedInput.CheckLastTagWas(0); - return this; - } - - /// - /// Parses as an UnknownFieldSet and merge it - /// with the set being built. This is just a small wrapper around - /// MergeFrom(ICodedInputStream). - /// - public Builder MergeFrom(ByteString data) - { - CodedInputStream input = data.CreateCodedInput(); - MergeFrom(input); - input.CheckLastTagWas(0); - return this; - } - - /// - /// Parses as an UnknownFieldSet and merge it - /// with the set being built. This is just a small wrapper around - /// MergeFrom(ICodedInputStream). - /// - public Builder MergeFrom(byte[] data) - { - CodedInputStream input = CodedInputStream.CreateInstance(data); - MergeFrom(input); - input.CheckLastTagWas(0); - return this; - } - - /// - /// Convenience method for merging a new field containing a single varint - /// value. This is used in particular when an unknown enum value is - /// encountered. - /// - public Builder MergeVarintField(int number, ulong value) - { - if (number == 0) - { - throw new ArgumentOutOfRangeException("number", "Zero is not a valid field number."); - } - GetFieldBuilder(number).AddVarint(value); - return this; - } - - /// - /// Merges the fields from into this set. - /// If a field number exists in both sets, the values in - /// will be appended to the values in this set. - /// - public Builder MergeFrom(UnknownFieldSet other) - { - if (other != DefaultInstance) - { - foreach (KeyValuePair entry in other.fields) - { - MergeField(entry.Key, entry.Value); - } - } - return this; - } - - /// - /// Checks if the given field number is present in the set. - /// - public bool HasField(int number) - { - if (number == 0) - { - throw new ArgumentOutOfRangeException("number", "Zero is not a valid field number."); - } - return number == lastFieldNumber || fields.ContainsKey(number); - } - - /// - /// Adds a field to the unknown field set. If a field with the same - /// number already exists, the two are merged. - /// - public Builder MergeField(int number, UnknownField field) - { - if (number == 0) - { - throw new ArgumentOutOfRangeException("number", "Zero is not a valid field number."); - } - if (HasField(number)) - { - GetFieldBuilder(number).MergeFrom(field); - } - else - { - // Optimization: We could call getFieldBuilder(number).mergeFrom(field) - // in this case, but that would create a copy of the Field object. - // We'd rather reuse the one passed to us, so call AddField() instead. - AddField(number, field); - } - return this; - } - - internal void MergeFrom(ICodedInputStream input, ExtensionRegistry extensionRegistry, IBuilder builder) - { - uint tag; - string name; - while (input.ReadTag(out tag, out name)) - { - if (tag == 0 && name != null) - { - FieldDescriptor fieldByName = builder.DescriptorForType.FindFieldByName(name); - if (fieldByName != null) - { - tag = WireFormat.MakeTag(fieldByName); - } - else - { - ExtensionInfo extension = extensionRegistry.FindByName(builder.DescriptorForType, name); - if (extension != null) - { - tag = WireFormat.MakeTag(extension.Descriptor); - } - } - } - if (tag == 0) - { - if (input.SkipField()) - { - continue; //can't merge unknown without field tag - } - break; - } - - if (!MergeFieldFrom(input, extensionRegistry, builder, tag, name)) - { - // end group tag - break; - } - } - } - - /// - /// Like - /// but parses a single field. - /// - /// The input to read the field from - /// Registry to use when an extension field is encountered - /// Builder to merge field into, if it's a known field - /// The tag, which should already have been read from the input - /// true unless the tag is an end-group tag - internal bool MergeFieldFrom(ICodedInputStream input, - ExtensionRegistry extensionRegistry, IBuilder builder, uint tag, - string fieldName) - { - if (tag == 0 && fieldName != null) - { - FieldDescriptor fieldByName = builder.DescriptorForType.FindFieldByName(fieldName); - if (fieldByName != null) - { - tag = WireFormat.MakeTag(fieldByName); - } - else - { - ExtensionInfo extension = extensionRegistry.FindByName(builder.DescriptorForType, fieldName); - if (extension != null) - { - tag = WireFormat.MakeTag(extension.Descriptor); - } - } - } - - MessageDescriptor type = builder.DescriptorForType; - if (type.Options.MessageSetWireFormat && tag == WireFormat.MessageSetTag.ItemStart) - { - MergeMessageSetExtensionFromCodedStream(input, extensionRegistry, builder); - return true; - } - - WireFormat.WireType wireType = WireFormat.GetTagWireType(tag); - int fieldNumber = WireFormat.GetTagFieldNumber(tag); - - FieldDescriptor field; - IMessageLite defaultFieldInstance = null; - - if (type.IsExtensionNumber(fieldNumber)) - { - ExtensionInfo extension = extensionRegistry[type, fieldNumber]; - if (extension == null) - { - field = null; - } - else - { - field = extension.Descriptor; - defaultFieldInstance = extension.DefaultInstance; - } - } - else - { - field = type.FindFieldByNumber(fieldNumber); - } - - // Unknown field or wrong wire type. Skip. - if (field == null) - { - return MergeFieldFrom(tag, input); - } - if (wireType != WireFormat.GetWireType(field)) - { - WireFormat.WireType expectedType = WireFormat.GetWireType(field.FieldType); - if (wireType == expectedType) - { - //Allowed as of 2.3, this is unpacked data for a packed array - } - else if (field.IsRepeated && wireType == WireFormat.WireType.LengthDelimited && - (expectedType == WireFormat.WireType.Varint || expectedType == WireFormat.WireType.Fixed32 || - expectedType == WireFormat.WireType.Fixed64)) - { - //Allowed as of 2.3, this is packed data for an unpacked array - } - else - { - return MergeFieldFrom(tag, input); - } - } - - switch (field.FieldType) - { - case FieldType.Group: - case FieldType.Message: - { - IBuilderLite subBuilder = (defaultFieldInstance != null) - ? defaultFieldInstance.WeakCreateBuilderForType() - : builder.CreateBuilderForField(field); - if (!field.IsRepeated) - { - subBuilder.WeakMergeFrom((IMessageLite) builder[field]); - if (field.FieldType == FieldType.Group) - { - input.ReadGroup(field.FieldNumber, subBuilder, extensionRegistry); - } - else - { - input.ReadMessage(subBuilder, extensionRegistry); - } - builder[field] = subBuilder.WeakBuild(); - } - else - { - List list = new List(); - if (field.FieldType == FieldType.Group) - { - input.ReadGroupArray(tag, fieldName, list, subBuilder.WeakDefaultInstanceForType, - extensionRegistry); - } - else - { - input.ReadMessageArray(tag, fieldName, list, subBuilder.WeakDefaultInstanceForType, - extensionRegistry); - } - - foreach (IMessageLite m in list) - { - builder.WeakAddRepeatedField(field, m); - } - return true; - } - break; - } - case FieldType.Enum: - { - if (!field.IsRepeated) - { - object unknown; - IEnumLite value = null; - if (input.ReadEnum(ref value, out unknown, field.EnumType)) - { - builder[field] = value; - } - else if (unknown is int) - { - MergeVarintField(fieldNumber, (ulong) (int) unknown); - } - } - else - { - ICollection unknown; - List list = new List(); - input.ReadEnumArray(tag, fieldName, list, out unknown, field.EnumType); - - foreach (IEnumLite en in list) - { - builder.WeakAddRepeatedField(field, en); - } - - if (unknown != null) - { - foreach (object oval in unknown) - { - if (oval is int) - { - MergeVarintField(fieldNumber, (ulong) (int) oval); - } - } - } - } - break; - } - default: - { - if (!field.IsRepeated) - { - object value = null; - if (input.ReadPrimitiveField(field.FieldType, ref value)) - { - builder[field] = value; - } - } - else - { - List list = new List(); - input.ReadPrimitiveArray(field.FieldType, tag, fieldName, list); - foreach (object oval in list) - { - builder.WeakAddRepeatedField(field, oval); - } - } - break; - } - } - return true; - } - - /// - /// Called by MergeFieldFrom to parse a MessageSet extension. - /// - private void MergeMessageSetExtensionFromCodedStream(ICodedInputStream input, - ExtensionRegistry extensionRegistry, IBuilder builder) - { - MessageDescriptor type = builder.DescriptorForType; - - // The wire format for MessageSet is: - // message MessageSet { - // repeated group Item = 1 { - // required int32 typeId = 2; - // required bytes message = 3; - // } - // } - // "typeId" is the extension's field number. The extension can only be - // a message type, where "message" contains the encoded bytes of that - // message. - // - // In practice, we will probably never see a MessageSet item in which - // the message appears before the type ID, or where either field does not - // appear exactly once. However, in theory such cases are valid, so we - // should be prepared to accept them. - - int typeId = 0; - ByteString rawBytes = null; // If we encounter "message" before "typeId" - IBuilderLite subBuilder = null; - FieldDescriptor field = null; - - uint lastTag = WireFormat.MessageSetTag.ItemStart; - uint tag; - string name; - while (input.ReadTag(out tag, out name)) - { - if (tag == 0 && name != null) - { - if (name == "type_id") - { - tag = WireFormat.MessageSetTag.TypeID; - } - else if (name == "message") - { - tag = WireFormat.MessageSetTag.Message; - } - } - if (tag == 0) - { - if (input.SkipField()) - { - continue; //can't merge unknown without field tag - } - break; - } - - lastTag = tag; - if (tag == WireFormat.MessageSetTag.TypeID) - { - typeId = 0; - // Zero is not a valid type ID. - if (input.ReadInt32(ref typeId) && typeId != 0) - { - ExtensionInfo extension = extensionRegistry[type, typeId]; - if (extension != null) - { - field = extension.Descriptor; - subBuilder = extension.DefaultInstance.WeakCreateBuilderForType(); - IMessageLite originalMessage = (IMessageLite) builder[field]; - if (originalMessage != null) - { - subBuilder.WeakMergeFrom(originalMessage); - } - if (rawBytes != null) - { - // We already encountered the message. Parse it now. - // TODO(jonskeet): Check this is okay. It's subtly different from the Java, as it doesn't create an input stream from rawBytes. - // In fact, why don't we just call MergeFrom(rawBytes)? And what about the extension registry? - subBuilder.WeakMergeFrom(rawBytes.CreateCodedInput()); - rawBytes = null; - } - } - else - { - // Unknown extension number. If we already saw data, put it - // in rawBytes. - if (rawBytes != null) - { - MergeField(typeId, UnknownField.CreateBuilder().AddLengthDelimited(rawBytes).Build()); - rawBytes = null; - } - } - } - } - else if (tag == WireFormat.MessageSetTag.Message) - { - if (subBuilder != null) - { - // We already know the type, so we can parse directly from the input - // with no copying. Hooray! - input.ReadMessage(subBuilder, extensionRegistry); - } - else if (input.ReadBytes(ref rawBytes)) - { - if (typeId != 0) - { - // We don't know how to parse this. Ignore it. - MergeField(typeId, - UnknownField.CreateBuilder().AddLengthDelimited(rawBytes).Build()); - } - } - } - else - { - // Unknown tag. Skip it. - if (!input.SkipField()) - { - break; // end of group - } - } - } - - if (lastTag != WireFormat.MessageSetTag.ItemEnd) - { - throw InvalidProtocolBufferException.InvalidEndTag(); - } - - if (subBuilder != null) - { - builder[field] = subBuilder.WeakBuild(); - } - } - - #region IBuilderLite Members - - bool IBuilderLite.IsInitialized - { - get { return fields != null; } - } - - IBuilderLite IBuilderLite.WeakClear() - { - return Clear(); - } - - IBuilderLite IBuilderLite.WeakMergeFrom(IMessageLite message) - { - return MergeFrom((UnknownFieldSet) message); - } - - IBuilderLite IBuilderLite.WeakMergeFrom(ByteString data) - { - return MergeFrom(data); - } - - IBuilderLite IBuilderLite.WeakMergeFrom(ByteString data, ExtensionRegistry registry) - { - return MergeFrom(data); - } - - IBuilderLite IBuilderLite.WeakMergeFrom(ICodedInputStream input) - { - return MergeFrom(input); - } - - IBuilderLite IBuilderLite.WeakMergeFrom(ICodedInputStream input, ExtensionRegistry registry) - { - return MergeFrom(input); - } - - IMessageLite IBuilderLite.WeakBuild() - { - return Build(); - } - - IMessageLite IBuilderLite.WeakBuildPartial() - { - return Build(); - } - - IBuilderLite IBuilderLite.WeakClone() - { - return Build().WeakToBuilder(); - } - - IMessageLite IBuilderLite.WeakDefaultInstanceForType - { - get { return DefaultInstance; } - } - - #endregion - } - } -} \ No newline at end of file diff --git a/csharp/src/ProtocolBuffers/WireFormat.cs b/csharp/src/ProtocolBuffers/WireFormat.cs index b9daa328..87f7c358 100644 --- a/csharp/src/ProtocolBuffers/WireFormat.cs +++ b/csharp/src/ProtocolBuffers/WireFormat.cs @@ -35,9 +35,9 @@ #endregion using System; -using Google.ProtocolBuffers.Descriptors; +using Google.Protobuf.Descriptors; -namespace Google.ProtocolBuffers +namespace Google.Protobuf { /// /// This class is used internally by the Protocol Buffer Library and generated diff --git a/src/google/protobuf/compiler/csharp/csharp_enum_field.cc b/src/google/protobuf/compiler/csharp/csharp_enum_field.cc index 8865702d..ee9d6a1d 100644 --- a/src/google/protobuf/compiler/csharp/csharp_enum_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_enum_field.cc @@ -61,7 +61,7 @@ void EnumFieldGenerator::GenerateParsingCode(io::Printer* printer) { void EnumFieldGenerator::GenerateSerializationCode(io::Printer* printer) { printer->Print(variables_, "if ($has_property_check$) {\n" - " output.WriteEnum($number$, fieldNames[$field_ordinal$], (long) $property_name$, $property_name$);\n" + " output.WriteEnum($number$, fieldNames[$field_ordinal$], $property_name$);\n" "}\n"); } @@ -69,7 +69,7 @@ void EnumFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { printer->Print( variables_, "if ($has_property_check$) {\n" - " size += pb::CodedOutputStream.ComputeEnumSize($number$, (long) $property_name$);\n" + " size += pb::CodedOutputStream.ComputeEnumSize($number$, $property_name$);\n" "}\n"); } @@ -87,8 +87,8 @@ void EnumOneofFieldGenerator::GenerateParsingCode(io::Printer* printer) { variables_, "$type_name$ enumValue = $default_value$;\n" "if(input.ReadEnum(ref enumValue)) {\n" - " result.$oneof_name$_ = enumValue;\n" - " result.$oneof_name$Case_ = $oneof_property_name$OneofCase.$property_name$;\n" + " $oneof_name$_ = enumValue;\n" + " $oneof_name$Case_ = $oneof_property_name$OneofCase.$property_name$;\n" "}\n"); } diff --git a/src/google/protobuf/compiler/csharp/csharp_field_base.cc b/src/google/protobuf/compiler/csharp/csharp_field_base.cc index 367e54c2..ec0d51ca 100644 --- a/src/google/protobuf/compiler/csharp/csharp_field_base.cc +++ b/src/google/protobuf/compiler/csharp/csharp_field_base.cc @@ -38,6 +38,7 @@ #include #include #include +#include #include #include @@ -51,6 +52,11 @@ namespace csharp { void FieldGeneratorBase::SetCommonFieldVariables( map* variables) { + // Note: this will be valid even though the tag emitted for packed and unpacked versions of + // repeated fields varies by wire format. The wire format is encoded in the bottom 3 bits, which + // never effects the tag size. + int tagSize = internal::WireFormat::TagSize(descriptor_->number(), descriptor_->type()); + (*variables)["tag_size"] = SimpleItoa(tagSize); (*variables)["property_name"] = property_name(); (*variables)["type_name"] = type_name(); (*variables)["name"] = name(); @@ -65,15 +71,10 @@ void FieldGeneratorBase::SetCommonFieldVariables( (*variables)["capitalized_type_name"] = capitalized_type_name(); (*variables)["number"] = number(); (*variables)["field_ordinal"] = field_ordinal(); - if (SupportFieldPresence(descriptor_->file())) { - (*variables)["has_property_check"] = "has" + (*variables)["property_name"]; - (*variables)["other_has_property_check"] = "other.Has" + (*variables)["property_name"]; - } else { - (*variables)["has_property_check"] = - (*variables)["property_name"] + " != " + (*variables)["default_value"]; - (*variables)["other_has_property_check"] = "other." + - (*variables)["property_name"] + " != " + (*variables)["default_value"]; - } + (*variables)["has_property_check"] = + (*variables)["property_name"] + " != " + (*variables)["default_value"]; + (*variables)["other_has_property_check"] = "other." + + (*variables)["property_name"] + " != " + (*variables)["default_value"]; } void FieldGeneratorBase::SetCommonOneofFieldVariables( diff --git a/src/google/protobuf/compiler/csharp/csharp_message.cc b/src/google/protobuf/compiler/csharp/csharp_message.cc index 1defcf94..b5929bcd 100644 --- a/src/google/protobuf/compiler/csharp/csharp_message.cc +++ b/src/google/protobuf/compiler/csharp/csharp_message.cc @@ -179,10 +179,14 @@ void MessageGenerator::Generate(io::Printer* printer) { WriteGeneratedCodeAttributes(printer); printer->Print( vars, - "$access_level$ sealed partial class $class_name$ : pb::IMessage<$class_name$> {\n"); + "$access_level$ sealed partial class $class_name$ : pb::IMessage<$class_name$>, global::System.IEquatable<$class_name$> {\n"); printer->Indent(); // All static fields and properties + printer->Print( + vars, + "private static readonly pb::MessageParser<$class_name$> _parser = new pb::MessageParser<$class_name$>(() => new $class_name$());\n" + "public static pb::MessageParser<$class_name$> Parser { get { return _parser; } }\n\n"); printer->Print( "private static readonly string[] _fieldNames = " "new string[] { $slash$$field_names$$slash$ };\n", @@ -204,7 +208,7 @@ void MessageGenerator::Generate(io::Printer* printer) { " get { return $umbrella_class_name$.internal__$identifier$__Descriptor; }\n" "}\n" "\n" - "protected override pb::FieldAccess.FieldAccessorTable<$class_name$> InternalFieldAccessors {\n" + "public pb::FieldAccess.FieldAccessorTable<$class_name$> Fields {\n" " get { return $umbrella_class_name$.internal__$identifier$__FieldAccessorTable; }\n" "}\n" "\n"); @@ -217,7 +221,7 @@ void MessageGenerator::Generate(io::Printer* printer) { printer->Print( vars, "public $class_name$($class_name$ other) {\n" - " MergeWith(other);\n" + " MergeFrom(other);\n" "}\n"); // Merge ctor. // Fields/properties @@ -259,15 +263,16 @@ void MessageGenerator::Generate(io::Printer* printer) { "public $property_name$OneofCase $property_name$Case {\n" " get { return $name$Case_; }\n" "}\n\n" - "private Clear$property_name$() {;\n" - " $name$Case_ = $property_name$OneofCase.None;" - " $name$_ = null;" + "public void Clear$property_name$() {\n" + " $name$Case_ = $property_name$OneofCase.None;\n" + " $name$_ = null;\n" "}\n\n"); } // TODO(jonskeet): Map properties // Standard methods + GenerateFrameworkMethods(printer); GenerateMessageSerializationMethods(printer); GenerateMergingMethods(printer); @@ -298,6 +303,51 @@ void MessageGenerator::Generate(io::Printer* printer) { } +void MessageGenerator::GenerateFrameworkMethods(io::Printer* printer) { + map vars; + vars["class_name"] = class_name(); + + // Equality + printer->Print( + vars, + "public override bool Equals(object other) {\n" + " return Equals(other as $class_name$);\n" + "}\n\n" + "public bool Equals($class_name$ other) {\n" + " if (ReferenceEquals(other, null)) {\n" + " return false;\n" + " }\n" + " if (ReferenceEquals(other, this)) {\n" + " return true;\n" + " }\n"); + printer->Indent(); + for (int i = 0; i < descriptor_->field_count(); i++) { + scoped_ptr generator( + CreateFieldGeneratorInternal(descriptor_->field(i))); + generator->WriteEquals(printer); + } + printer->Outdent(); + printer->Print( + " return true;\n" + "}\n\n"); + + // GetHashCode + printer->Print( + "public override int GetHashCode() {\n" + " int hash = 0;\n"); + printer->Indent(); + for (int i = 0; i < descriptor_->field_count(); i++) { + scoped_ptr generator( + CreateFieldGeneratorInternal(descriptor_->field(i))); + generator->WriteHash(printer); + } + printer->Print("return hash;\n"); + printer->Outdent(); + printer->Print("}\n\n"); + + // TODO(jonskeet): ToString. +} + void MessageGenerator::GenerateMessageSerializationMethods(io::Printer* printer) { printer->Print( "public void WriteTo(pb::ICodedOutputStream output) {\n"); @@ -316,7 +366,7 @@ void MessageGenerator::GenerateMessageSerializationMethods(io::Printer* printer) printer->Print( "}\n" "\n" - "public int CalculateSerializedSize() {\n"); + "public int CalculateSize() {\n"); printer->Indent(); printer->Print("int size = 0;\n"); for (int i = 0; i < descriptor_->field_count(); i++) { @@ -338,7 +388,7 @@ void MessageGenerator::GenerateMergingMethods(io::Printer* printer) { printer->Print( vars, - "public void MergeWith($class_name$ other) {\n"); + "public void MergeFrom($class_name$ other) {\n"); printer->Indent(); printer->Print( "if (other == null) {\n" @@ -378,39 +428,38 @@ void MessageGenerator::GenerateMergingMethods(io::Printer* printer) { printer->Print( "uint tag;\n" "string fieldName;\n" - "while (input.ReadTag(out tag, out fieldName)) {\n" - " if (tag == 0 && fieldName != null) {"); - printer->Indent(); + "while (input.ReadTag(out tag, out fieldName)) {\n"); printer->Indent(); printer->Print( - "int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.String.String.Ordinal);\n" - "if (fieldOrdinal >= 0) {\n" - " tag = _fieldTags[fieldOrdinal];\n" + "if (tag == 0 && fieldName != null) {\n" + " int fieldOrdinal = global::System.Array.BinarySearch(_fieldNames, fieldName, global::System.StringComparer.Ordinal);\n" + " if (fieldOrdinal >= 0) {\n" + " tag = _fieldTags[fieldOrdinal];\n" + " }\n" "}\n" "switch(tag) {\n"); printer->Indent(); printer->Print( - "case 0: {\n" // 0 signals EOF / limit reached + "case 0:\n" // 0 signals EOF / limit reached " throw pb::InvalidProtocolBufferException.InvalidTag();\n" - "}\n" "default:\n" " if (pb::WireFormat.IsEndGroupTag(tag)) {\n" " return;\n" " }\n" - " break;"); // Note: we're ignoring unknown fields here. + " break;\n"); // Note: we're ignoring unknown fields here. for (int i = 0; i < fields_by_number().size(); i++) { const FieldDescriptor* field = fields_by_number()[i]; internal::WireFormatLite::WireType wt = internal::WireFormat::WireTypeForFieldType(field->type()); uint32 tag = internal::WireFormatLite::MakeTag(field->number(), wt); - // TODO(jonskeet): Understand what this is trying to do - if (field->is_repeated() - && (wt == internal::WireFormatLite::WIRETYPE_VARINT - || wt == internal::WireFormatLite::WIRETYPE_FIXED32 - || wt == internal::WireFormatLite::WIRETYPE_FIXED64)) { + // Handle both packed and unpacked repeated fields with the same Read*Array call; + // the two generated cases are the packed and unpacked tags. + // TODO(jonskeet): Check that is_packable is equivalent to is_repeated && wt in { VARINT, FIXED32, FIXED64 }. + // It looks like it is... + if (field->is_packable()) { printer->Print( - "case $number$:\n", - "number", + "case $packed_tag$:\n", + "packed_tag", SimpleItoa( internal::WireFormatLite::MakeTag( field->number(), @@ -429,8 +478,6 @@ void MessageGenerator::GenerateMergingMethods(io::Printer* printer) { printer->Outdent(); printer->Print("}\n"); // switch printer->Outdent(); - printer->Print("}\n"); // if - printer->Outdent(); printer->Print("}\n"); // while printer->Outdent(); printer->Print("}\n\n"); // method diff --git a/src/google/protobuf/compiler/csharp/csharp_message.h b/src/google/protobuf/compiler/csharp/csharp_message.h index f5f41c73..eb90ce67 100644 --- a/src/google/protobuf/compiler/csharp/csharp_message.h +++ b/src/google/protobuf/compiler/csharp/csharp_message.h @@ -50,6 +50,7 @@ class MessageGenerator : public SourceGeneratorBase { MessageGenerator(const Descriptor* descriptor); ~MessageGenerator(); + void GenerateFrameworkMethods(io::Printer* printer); void GenerateStaticVariables(io::Printer* printer); void GenerateStaticVariableInitializers(io::Printer* printer); void Generate(io::Printer* printer); diff --git a/src/google/protobuf/compiler/csharp/csharp_message_field.cc b/src/google/protobuf/compiler/csharp/csharp_message_field.cc index 90aa201b..4b7ac88f 100644 --- a/src/google/protobuf/compiler/csharp/csharp_message_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_message_field.cc @@ -49,8 +49,8 @@ namespace csharp { MessageFieldGenerator::MessageFieldGenerator(const FieldDescriptor* descriptor, int fieldOrdinal) : FieldGeneratorBase(descriptor, fieldOrdinal) { - variables_["has_property_check"] = property_name() + "_ != null"; - variables_["has_not_property_check"] = property_name() + "_ == null"; + variables_["has_property_check"] = name() + "_ != null"; + variables_["has_not_property_check"] = name() + "_ == null"; } MessageFieldGenerator::~MessageFieldGenerator() { @@ -66,7 +66,7 @@ void MessageFieldGenerator::GenerateMembers(io::Printer* printer) { variables_, "public $type_name$ $property_name$ {\n" " get { return $name$_; }\n" - " set { return $name$_ = value; }\n" + " set { $name$_ = value; }\n" "}\n"); } @@ -74,17 +74,17 @@ void MessageFieldGenerator::GenerateMergingCode(io::Printer* printer) { printer->Print( variables_, "if (other.$has_property_check$) {\n" - " if ($has_not_property_check) {\n" + " if ($has_not_property_check$) {\n" " $name$_ = new $type_name$();\n" " }\n" - " $property_name$.MergeWith(other.$property_name);\n" + " $property_name$.MergeFrom(other.$property_name$);\n" "}\n"); } void MessageFieldGenerator::GenerateParsingCode(io::Printer* printer) { printer->Print( variables_, - "if ($has_not_property_check) {\n" + "if ($has_not_property_check$) {\n" " $name$_ = new $type_name$();\n" "}\n" "input.ReadMessage($name$_);\n"); // No need to support TYPE_GROUP... @@ -110,12 +110,12 @@ void MessageFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { void MessageFieldGenerator::WriteHash(io::Printer* printer) { printer->Print( variables_, - "if ($has_property_check$) hash ^= $name$_.GetHashCode();\n"); + "if ($has_property_check$) hash ^= $property_name$.GetHashCode();\n"); } void MessageFieldGenerator::WriteEquals(io::Printer* printer) { printer->Print( variables_, - "if (!object.Equals($property_name$_, other.$property_name$_)) return false;\n"); + "if (!object.Equals($property_name$, other.$property_name$)) return false;"); } void MessageFieldGenerator::WriteToString(io::Printer* printer) { variables_["field_name"] = GetFieldName(descriptor_); @@ -140,10 +140,10 @@ void MessageOneofFieldGenerator::GenerateMembers(io::Printer* printer) { variables_, "public $type_name$ $property_name$ {\n" " get { return $has_property_check$ ? ($type_name$) $oneof_name$_ : null; }\n" - " set { \n" - " $name$_ = value;" - " $oneof_name$Case_ = value == null ? $oneof_property_name$Case.None : $oneof_property_name$Case.$property_name$; }\n" - " } \n" + " set {\n" + " $oneof_name$_ = value;\n" + " $oneof_name$Case_ = value == null ? $oneof_property_name$OneofCase.None : $oneof_property_name$OneofCase.$property_name$;\n" + " }\n" "}\n"); } @@ -151,12 +151,12 @@ void MessageOneofFieldGenerator::GenerateParsingCode(io::Printer* printer) { // TODO(jonskeet): We may be able to do better than this printer->Print( variables_, - "$type_name$ subBuilder = new type_name$();\n" + "$type_name$ subBuilder = new $type_name$();\n" "if ($has_property_check$) {\n" - " subBuilder.MergeWith($property_name$);\n" + " subBuilder.MergeFrom($property_name$);\n" "}\n" "input.ReadMessage(subBuilder);\n" // No support of TYPE_GROUP - "$oneof_property_name$ = subBuilder;\n"); + "$property_name$ = subBuilder;\n"); } void MessageOneofFieldGenerator::WriteToString(io::Printer* printer) { diff --git a/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc b/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc index bc4858fc..f2b66a00 100644 --- a/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_primitive_field.cc @@ -93,7 +93,7 @@ void PrimitiveFieldGenerator::GenerateMergingCode(io::Printer* printer) { void PrimitiveFieldGenerator::GenerateParsingCode(io::Printer* printer) { printer->Print( variables_, - "input.Read$capitalized_type_name$(ref result.$name$_);\n"); + "input.Read$capitalized_type_name$(ref $name$_);\n"); } void PrimitiveFieldGenerator::GenerateSerializationCode(io::Printer* printer) { @@ -115,9 +115,7 @@ void PrimitiveFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { void PrimitiveFieldGenerator::WriteHash(io::Printer* printer) { printer->Print( variables_, - "if ($has_property_check$) {\n" - " hash ^= $property_name$.GetHashCode();\n" - "}\n"); + "if ($has_property_check$) hash ^= $property_name$.GetHashCode();\n"); } void PrimitiveFieldGenerator::WriteEquals(io::Printer* printer) { printer->Print( @@ -147,17 +145,17 @@ void PrimitiveOneofFieldGenerator::GenerateMembers(io::Printer* printer) { variables_, "public $type_name$ $property_name$ {\n" " get { return $has_property_check$ ? ($type_name$) $oneof_name$_ : $default_value$; }\n" - " set {"); + " set {\n"); if (is_value_type) { printer->Print( variables_, - " $oneof_name$_ = value;\n" - " $oneof_name$Case_ = $oneof_property_name$Case.$property_name$;\n"); + " $oneof_name$_ = value;\n" + " $oneof_name$Case_ = $oneof_property_name$OneofCase.$property_name$;\n"); } else { printer->Print( variables_, - " $oneof_name$_ = value ?? $default_value$;\n" - " $oneof_name$Case_ = value == null ? $oneof_property_name$Case.None : $oneof_property_name$Case.$property_name$;\n"); + " $oneof_name$_ = value ?? $default_value$;\n" + " $oneof_name$Case_ = value == null ? $oneof_property_name$OneofCase.None : $oneof_property_name$OneofCase.$property_name$;\n"); } printer->Print( " }\n" diff --git a/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc b/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc index f5d5a126..ebbbf3be 100644 --- a/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_repeated_enum_field.cc @@ -49,6 +49,7 @@ namespace csharp { RepeatedEnumFieldGenerator::RepeatedEnumFieldGenerator( const FieldDescriptor* descriptor, int fieldOrdinal) : FieldGeneratorBase(descriptor, fieldOrdinal) { + variables_["packed"] = descriptor->is_packed() ? "Packed" : ""; } RepeatedEnumFieldGenerator::~RepeatedEnumFieldGenerator() { @@ -75,27 +76,21 @@ void RepeatedEnumFieldGenerator::GenerateMergingCode(io::Printer* printer) { void RepeatedEnumFieldGenerator::GenerateParsingCode(io::Printer* printer) { printer->Print( variables_, - "input.ReadEnumArray<$type_name$>(tag, fieldName, result.$name$_);\n"); + "input.ReadEnumArray<$type_name$>(tag, fieldName, $name$_);\n"); } void RepeatedEnumFieldGenerator::GenerateSerializationCode(io::Printer* printer) { // TODO(jonskeet): Originally, this checked for Count > 0 first. // The Write* call should make that cheap though - no need to generate it every time. - if (descriptor_->is_packed()) { - printer->Print( - variables_, - "output.WritePackedEnumArray($number$, fieldNames[$field_ordinal$], $name$_);\n"); - } else { - printer->Print(variables_, - "output.WriteEnumArray($number$, fieldNames[$field_ordinal$], $name$_);\n"); - } - printer->Print("}\n"); + printer->Print( + variables_, + "output.Write$packed$EnumArray($number$, fieldNames[$field_ordinal$], $name$_);\n"); } void RepeatedEnumFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer) { + // TODO(jonskeet): Move all this code into CodedOutputStream? It's a lot to repeat everywhere... printer->Print("{\n"); printer->Indent(); - // TODO(jonskeet): Move all this code into CodedOutputStream? It's a lot to repeat everywhere... printer->Print( variables_, "int dataSize = 0;\n" @@ -104,7 +99,7 @@ void RepeatedEnumFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer printer->Print( variables_, "foreach ($type_name$ element in $name$_) {\n" - " dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag((long) element);\n" + " dataSize += pb::CodedOutputStream.ComputeEnumSizeNoTag(element);\n" "}\n" "size += dataSize;\n"); int tagSize = internal::WireFormat::TagSize(descriptor_->number(), descriptor_->type()); @@ -127,15 +122,13 @@ void RepeatedEnumFieldGenerator::GenerateSerializedSizeCode(io::Printer* printer void RepeatedEnumFieldGenerator::WriteHash(io::Printer* printer) { printer->Print( variables_, - "foreach($type_name$ i in $name$_) {\n" - " hash ^= i.GetHashCode();\n" - "}\n"); + "hash ^= $name$_.GetHashCode();\n"); } void RepeatedEnumFieldGenerator::WriteEquals(io::Printer* printer) { printer->Print( variables_, - "if(!$name$_.Equals(other.$name$)) return false;\n"); + "if(!$name$_.Equals(other.$name$_)) return false;\n"); } void RepeatedEnumFieldGenerator::WriteToString(io::Printer* printer) { diff --git a/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc b/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc index 2a6a01f5..963f841e 100644 --- a/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_repeated_message_field.cc @@ -64,21 +64,6 @@ void RepeatedMessageFieldGenerator::GenerateMembers(io::Printer* printer) { "public pbc::RepeatedField<$type_name$> $property_name$ {\n" " get { return $name$_; }\n" "}\n"); - - // TODO(jonskeet): Redundant API calls? Possibly - include for portability though. Maybe create an option. - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public int $property_name$Count {\n" - " get { return $name$_.Count; }\n" - "}\n"); - - AddDeprecatedFlag(printer); - printer->Print( - variables_, - "public $type_name$ Get$property_name$(int index) {\n" - " return $name$_[index];\n" - "}\n"); } void RepeatedMessageFieldGenerator::GenerateMergingCode(io::Printer* printer) { @@ -90,7 +75,7 @@ void RepeatedMessageFieldGenerator::GenerateMergingCode(io::Printer* printer) { void RepeatedMessageFieldGenerator::GenerateParsingCode(io::Printer* printer) { printer->Print( variables_, - "input.ReadMessageArray(tag, fieldName, $name$_);\n"); + "input.ReadMessageArray(tag, fieldName, $name$_, $type_name$.Parser);\n"); } void RepeatedMessageFieldGenerator::GenerateSerializationCode(io::Printer* printer) { @@ -105,7 +90,7 @@ void RepeatedMessageFieldGenerator::GenerateSerializedSizeCode(io::Printer* prin // TODO(jonskeet): Put this into CodedOutputStream. printer->Print( variables_, - "foreach ($type_name$ element in $property_name$) {\n" + "foreach ($type_name$ element in $name$_) {\n" " size += pb::CodedOutputStream.ComputeMessageSize($number$, element);\n" "}\n"); } @@ -113,15 +98,15 @@ void RepeatedMessageFieldGenerator::GenerateSerializedSizeCode(io::Printer* prin void RepeatedMessageFieldGenerator::WriteHash(io::Printer* printer) { printer->Print( variables_, - "foreach($type_name$ i in $name$_) {\n" - " hash ^= i.GetHashCode();\n" - "}\n"); + "hash ^= $name$_.GetHashCode();\n"); } + void RepeatedMessageFieldGenerator::WriteEquals(io::Printer* printer) { printer->Print( variables_, - "if(!$name$_.Equals(other.$name$)) return false;\n"); + "if(!$name$_.Equals(other.$name$_)) return false;\n"); } + void RepeatedMessageFieldGenerator::WriteToString(io::Printer* printer) { variables_["field_name"] = GetFieldName(descriptor_); printer->Print( diff --git a/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc b/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc index 2001b849..0a91c3c6 100644 --- a/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc +++ b/src/google/protobuf/compiler/csharp/csharp_repeated_primitive_field.cc @@ -92,7 +92,7 @@ void RepeatedPrimitiveFieldGenerator::GenerateSerializationCode( void RepeatedPrimitiveFieldGenerator::GenerateSerializedSizeCode( io::Printer* printer) { - // TODO(jonskeet): Get rid of most of this - move it into the runtime. + // TODO(jonskeet): Do this in the runtime if possible. It's a pain, but it must be feasible... printer->Print("{\n"); printer->Indent(); printer->Print("int dataSize = 0;\n"); @@ -100,7 +100,7 @@ void RepeatedPrimitiveFieldGenerator::GenerateSerializedSizeCode( if (fixedSize == -1) { printer->Print( variables_, - "foreach ($type_name$ element in $property_name$List) {\n" + "foreach ($type_name$ element in $name$_) {\n" " dataSize += pb::CodedOutputStream.Compute$capitalized_type_name$SizeNoTag(element);\n" "}\n"); } else { @@ -128,14 +128,12 @@ void RepeatedPrimitiveFieldGenerator::GenerateSerializedSizeCode( void RepeatedPrimitiveFieldGenerator::WriteHash(io::Printer* printer) { printer->Print( variables_, - "foreach($type_name$ i in $name$_)\n {" - " hash ^= i.GetHashCode();\n" - "}\n"); + "hash ^= $name$_.GetHashCode();\n"); } void RepeatedPrimitiveFieldGenerator::WriteEquals(io::Printer* printer) { printer->Print( variables_, - "if(!$name$_.Equals(other.$name$)) return false;\n"); + "if(!$name$_.Equals(other.$name$_)) return false;\n"); } void RepeatedPrimitiveFieldGenerator::WriteToString(io::Printer* printer) { printer->Print(variables_, diff --git a/src/google/protobuf/descriptor.proto b/src/google/protobuf/descriptor.proto index 20a60080..97741b6a 100644 --- a/src/google/protobuf/descriptor.proto +++ b/src/google/protobuf/descriptor.proto @@ -42,7 +42,7 @@ syntax = "proto2"; package google.protobuf; option java_package = "com.google.protobuf"; option java_outer_classname = "DescriptorProtos"; -option csharp_namespace = "Google.ProtocolBuffers.DescriptorProtos"; +option csharp_namespace = "Google.Protobuf.DescriptorProtos"; option objc_class_prefix = "GPB"; // descriptor.proto must be optimized for speed because reflection-based diff --git a/src/google/protobuf/unittest_import_proto3.proto b/src/google/protobuf/unittest_import_proto3.proto new file mode 100644 index 00000000..59673eaf --- /dev/null +++ b/src/google/protobuf/unittest_import_proto3.proto @@ -0,0 +1,68 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Author: kenton@google.com (Kenton Varda) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. +// +// A proto file which is imported by unittest_proto3.proto to test importing. + +syntax = "proto3"; + +// We don't put this in a package within proto2 because we need to make sure +// that the generated code doesn't depend on being in the proto2 namespace. +// In test_util.h we do +// "using namespace unittest_import = protobuf_unittest_import". +package protobuf_unittest_import; + +option optimize_for = SPEED; +option cc_enable_arenas = true; + +// Exercise the java_package option. +option java_package = "com.google.protobuf.test"; +option csharp_namespace = "Google.Protobuf.TestProtos"; + +// Do not set a java_outer_classname here to verify that Proto2 works without +// one. + +// Test public import +import public "google/protobuf/unittest_import_public_proto3.proto"; + +message ImportMessage { + int32 d = 1; +} + +enum ImportEnum { + IMPORT_ENUM_UNSPECIFIED = 0; + IMPORT_FOO = 7; + IMPORT_BAR = 8; + IMPORT_BAZ = 9; +} + diff --git a/src/google/protobuf/unittest_import_public_proto3.proto b/src/google/protobuf/unittest_import_public_proto3.proto new file mode 100644 index 00000000..d6f11e28 --- /dev/null +++ b/src/google/protobuf/unittest_import_public_proto3.proto @@ -0,0 +1,42 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Author: liujisi@google.com (Pherl Liu) + +syntax = "proto3"; + +package protobuf_unittest_import; + +option java_package = "com.google.protobuf.test"; +option csharp_namespace = "Google.Protobuf.TestProtos"; + +message PublicImportMessage { + int32 e = 1; +} diff --git a/src/google/protobuf/unittest_proto3.proto b/src/google/protobuf/unittest_proto3.proto new file mode 100644 index 00000000..f59d2178 --- /dev/null +++ b/src/google/protobuf/unittest_proto3.proto @@ -0,0 +1,388 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Author: kenton@google.com (Kenton Varda) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. +// +// A proto file we will use for unit testing. + +syntax = "proto3"; + +// Some generic_services option(s) added automatically. +// See: http://go/proto2-generic-services-default +option cc_generic_services = true; // auto-added +option java_generic_services = true; // auto-added +option py_generic_services = true; // auto-added +option cc_enable_arenas = true; +option csharp_namespace = "Google.Protobuf.TestProtos"; + +import "google/protobuf/unittest_import_proto3.proto"; + +// We don't put this in a package within proto2 because we need to make sure +// that the generated code doesn't depend on being in the proto2 namespace. +// In test_util.h we do "using namespace unittest = protobuf_unittest". +package protobuf_unittest; + +// Protos optimized for SPEED use a strict superset of the generated code +// of equivalent ones optimized for CODE_SIZE, so we should optimize all our +// tests for speed unless explicitly testing code size optimization. +option optimize_for = SPEED; + +option java_outer_classname = "UnittestProto"; + +// This proto includes every type of field in both singular and repeated +// forms. +message TestAllTypes { + message NestedMessage { + // The field name "b" fails to compile in proto1 because it conflicts with + // a local variable named "b" in one of the generated methods. Doh. + // This file needs to compile in proto1 to test backwards-compatibility. + int32 bb = 1; + } + + enum NestedEnum { + NESTED_ENUM_UNSPECIFIED = 0; + FOO = 1; + BAR = 2; + BAZ = 3; + NEG = -1; // Intentionally negative. + } + + // Singular + int32 single_int32 = 1; + int64 single_int64 = 2; + uint32 single_uint32 = 3; + uint64 single_uint64 = 4; + sint32 single_sint32 = 5; + sint64 single_sint64 = 6; + fixed32 single_fixed32 = 7; + fixed64 single_fixed64 = 8; + sfixed32 single_sfixed32 = 9; + sfixed64 single_sfixed64 = 10; + float single_float = 11; + double single_double = 12; + bool single_bool = 13; + string single_string = 14; + bytes single_bytes = 15; + + NestedMessage single_nested_message = 18; + ForeignMessage single_foreign_message = 19; + protobuf_unittest_import.ImportMessage single_import_message = 20; + + NestedEnum single_nested_enum = 21; + ForeignEnum single_foreign_enum = 22; + protobuf_unittest_import.ImportEnum single_import_enum = 23; + + // Defined in unittest_import_public.proto + protobuf_unittest_import.PublicImportMessage + single_public_import_message = 26; + + // Repeated + repeated int32 repeated_int32 = 31; + repeated int64 repeated_int64 = 32; + repeated uint32 repeated_uint32 = 33; + repeated uint64 repeated_uint64 = 34; + repeated sint32 repeated_sint32 = 35; + repeated sint64 repeated_sint64 = 36; + repeated fixed32 repeated_fixed32 = 37; + repeated fixed64 repeated_fixed64 = 38; + repeated sfixed32 repeated_sfixed32 = 39; + repeated sfixed64 repeated_sfixed64 = 40; + repeated float repeated_float = 41; + repeated double repeated_double = 42; + repeated bool repeated_bool = 43; + repeated string repeated_string = 44; + repeated bytes repeated_bytes = 45; + + repeated NestedMessage repeated_nested_message = 48; + repeated ForeignMessage repeated_foreign_message = 49; + repeated protobuf_unittest_import.ImportMessage repeated_import_message = 50; + + repeated NestedEnum repeated_nested_enum = 51; + repeated ForeignEnum repeated_foreign_enum = 52; + repeated protobuf_unittest_import.ImportEnum repeated_import_enum = 53; + // Defined in unittest_import_public.proto + repeated protobuf_unittest_import.PublicImportMessage + repeated_public_import_message = 54; + + // For oneof test + oneof oneof_field { + uint32 oneof_uint32 = 111; + NestedMessage oneof_nested_message = 112; + string oneof_string = 113; + bytes oneof_bytes = 114; + } +} + +// This proto includes a recusively nested message. +message NestedTestAllTypes { + NestedTestAllTypes child = 1; + TestAllTypes payload = 2; + repeated NestedTestAllTypes repeated_child = 3; +} + +message TestDeprecatedFields { + int32 deprecated_int32 = 1 [deprecated=true]; +} + +// Define these after TestAllTypes to make sure the compiler can handle +// that. +message ForeignMessage { + int32 c = 1; +} + +enum ForeignEnum { + FOREIGN_UNSPECIFIED = 0; + FOREIGN_FOO = 4; + FOREIGN_BAR = 5; + FOREIGN_BAZ = 6; +} + +message TestReservedFields { + reserved 2, 15, 9 to 11; + reserved "bar", "baz"; +} + + +// Test that we can use NestedMessage from outside TestAllTypes. +message TestForeignNested { + TestAllTypes.NestedMessage foreign_nested = 1; +} + +// Test that really large tag numbers don't break anything. +message TestReallyLargeTagNumber { + // The largest possible tag number is 2^28 - 1, since the wire format uses + // three bits to communicate wire type. + int32 a = 1; + int32 bb = 268435455; +} + +message TestRecursiveMessage { + TestRecursiveMessage a = 1; + int32 i = 2; +} + +// Test that mutual recursion works. +message TestMutualRecursionA { + TestMutualRecursionB bb = 1; +} + +message TestMutualRecursionB { + TestMutualRecursionA a = 1; + int32 optional_int32 = 2; +} + + +// Test an enum that has multiple values with the same number. +enum TestEnumWithDupValue { + TEST_ENUM_WITH_DUP_VALUE_UNSPECIFIED = 0; + option allow_alias = true; + + FOO1 = 1; + BAR1 = 2; + BAZ = 3; + FOO2 = 1; + BAR2 = 2; +} + +// Test an enum with large, unordered values. +enum TestSparseEnum { + TEST_SPARSE_ENUM_UNSPECIFIED = 0; + SPARSE_A = 123; + SPARSE_B = 62374; + SPARSE_C = 12589234; + SPARSE_D = -15; + SPARSE_E = -53452; + // In proto3, value 0 must be the first one specified + // SPARSE_F = 0; + SPARSE_G = 2; +} + +// Test message with CamelCase field names. This violates Protocol Buffer +// standard style. +message TestCamelCaseFieldNames { + int32 PrimitiveField = 1; + string StringField = 2; + ForeignEnum EnumField = 3; + ForeignMessage MessageField = 4; + + repeated int32 RepeatedPrimitiveField = 7; + repeated string RepeatedStringField = 8; + repeated ForeignEnum RepeatedEnumField = 9; + repeated ForeignMessage RepeatedMessageField = 10; +} + + +// We list fields out of order, to ensure that we're using field number and not +// field index to determine serialization order. +message TestFieldOrderings { + string my_string = 11; + int64 my_int = 1; + float my_float = 101; + message NestedMessage { + int64 oo = 2; + // The field name "b" fails to compile in proto1 because it conflicts with + // a local variable named "b" in one of the generated methods. Doh. + // This file needs to compile in proto1 to test backwards-compatibility. + int32 bb = 1; + } + + NestedMessage single_nested_message = 200; +} + +message SparseEnumMessage { + TestSparseEnum sparse_enum = 1; +} + +// Test String and Bytes: string is for valid UTF-8 strings +message OneString { + string data = 1; +} + +message MoreString { + repeated string data = 1; +} + +message OneBytes { + bytes data = 1; +} + +message MoreBytes { + bytes data = 1; +} + +// Test int32, uint32, int64, uint64, and bool are all compatible +message Int32Message { + int32 data = 1; +} + +message Uint32Message { + uint32 data = 1; +} + +message Int64Message { + int64 data = 1; +} + +message Uint64Message { + uint64 data = 1; +} + +message BoolMessage { + bool data = 1; +} + +// Test oneofs. +message TestOneof { + oneof foo { + int32 foo_int = 1; + string foo_string = 2; + TestAllTypes foo_message = 3; + } +} + +// Test messages for packed fields + +message TestPackedTypes { + repeated int32 packed_int32 = 90 [packed = true]; + repeated int64 packed_int64 = 91 [packed = true]; + repeated uint32 packed_uint32 = 92 [packed = true]; + repeated uint64 packed_uint64 = 93 [packed = true]; + repeated sint32 packed_sint32 = 94 [packed = true]; + repeated sint64 packed_sint64 = 95 [packed = true]; + repeated fixed32 packed_fixed32 = 96 [packed = true]; + repeated fixed64 packed_fixed64 = 97 [packed = true]; + repeated sfixed32 packed_sfixed32 = 98 [packed = true]; + repeated sfixed64 packed_sfixed64 = 99 [packed = true]; + repeated float packed_float = 100 [packed = true]; + repeated double packed_double = 101 [packed = true]; + repeated bool packed_bool = 102 [packed = true]; + repeated ForeignEnum packed_enum = 103 [packed = true]; +} + +// A message with the same fields as TestPackedTypes, but without packing. Used +// to test packed <-> unpacked wire compatibility. +message TestUnpackedTypes { + repeated int32 unpacked_int32 = 90 [packed = false]; + repeated int64 unpacked_int64 = 91 [packed = false]; + repeated uint32 unpacked_uint32 = 92 [packed = false]; + repeated uint64 unpacked_uint64 = 93 [packed = false]; + repeated sint32 unpacked_sint32 = 94 [packed = false]; + repeated sint64 unpacked_sint64 = 95 [packed = false]; + repeated fixed32 unpacked_fixed32 = 96 [packed = false]; + repeated fixed64 unpacked_fixed64 = 97 [packed = false]; + repeated sfixed32 unpacked_sfixed32 = 98 [packed = false]; + repeated sfixed64 unpacked_sfixed64 = 99 [packed = false]; + repeated float unpacked_float = 100 [packed = false]; + repeated double unpacked_double = 101 [packed = false]; + repeated bool unpacked_bool = 102 [packed = false]; + repeated ForeignEnum unpacked_enum = 103 [packed = false]; +} + +message TestRepeatedScalarDifferentTagSizes { + // Parsing repeated fixed size values used to fail. This message needs to be + // used in order to get a tag of the right size; all of the repeated fields + // in TestAllTypes didn't trigger the check. + repeated fixed32 repeated_fixed32 = 12; + // Check for a varint type, just for good measure. + repeated int32 repeated_int32 = 13; + + // These have two-byte tags. + repeated fixed64 repeated_fixed64 = 2046; + repeated int64 repeated_int64 = 2047; + + // Three byte tags. + repeated float repeated_float = 262142; + repeated uint64 repeated_uint64 = 262143; +} + +message TestCommentInjectionMessage { + // */ <- This should not close the generated doc comment + string a = 1; +} + + +// Test that RPC services work. +message FooRequest {} +message FooResponse {} + +message FooClientMessage {} +message FooServerMessage{} + +service TestService { + rpc Foo(FooRequest) returns (FooResponse); + rpc Bar(BarRequest) returns (BarResponse); +} + + +message BarRequest {} +message BarResponse {} + -- cgit v1.2.3